diff --git a/onprc_billing/module.properties b/onprc_billing/module.properties index a7dc1e7e7..9a0ab55eb 100644 --- a/onprc_billing/module.properties +++ b/onprc_billing/module.properties @@ -1,5 +1,5 @@ ModuleClass: org.labkey.onprc_billing.ONPRC_BillingModule -SupportedDatabases: mssql +SupportedDatabases: mssql, pgsql License: Apache 2.0 LicenseURL: http://www.apache.org/licenses/LICENSE-2.0 -ManageVersion: false +ManageVersion: true diff --git a/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-0.000-25.000.sql b/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-0.000-25.000.sql new file mode 100644 index 000000000..c1f8aee7f --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-0.000-25.000.sql @@ -0,0 +1,1585 @@ +/* + * 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; + +--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 SERIAL NOT NULL, + date TIMESTAMP, + dataSources varchar(1000), + runBy userid, + comment varchar(4000), + + container ENTITYID NOT NULL, + createdBy USERID, + created TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + 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 SERIAL NOT NULL, + id varchar(100), + date TIMESTAMP, + 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 TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + 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 SERIAL NOT NULL, + name varchar(200), + category varchar(200), + comment varchar(4000), + active boolean default true, + + container ENTITYID NOT NULL, + createdBy USERID, + created TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + 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 SERIAL NOT NULL, + chargeId int, + unitcost double precision, + unit varchar(100), + startDate timestamp, + endDate timestamp, + + container ENTITYID NOT NULL, + createdBy USERID, + created TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + CONSTRAINT PK_chargeRates PRIMARY KEY (rowId) +); + +--contains records of project-specific exemptions to chargeRates +CREATE TABLE onprc_billing.chargeRateExemptions ( + rowId SERIAL NOT NULL, + project int, + chargeId int, + unitcost double precision, + unit varchar(100), + startDate timestamp, + endDate timestamp, + + container ENTITYID NOT NULL, + createdBy USERID, + created TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + CONSTRAINT PK_chargeRateExemptions PRIMARY KEY (rowId) +); + +--maps the account to be credited for each charged item +CREATE TABLE onprc_billing.creditAccount ( + rowId SERIAL NOT NULL, + chargeId int, + account int, + startDate timestamp, + endDate timestamp, + + container ENTITYID NOT NULL, + createdBy USERID, + created TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + 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 SERIAL NOT NULL, + id varchar(100), + date TIMESTAMP, + 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 TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + 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 SERIAL NOT NULL, + minAge int, + maxAge int, + + assignCondition int, + releaseCondition int, + chargeId int, + + active boolean default true, + objectid ENTITYID, + createdBy int, + created TIMESTAMP, + modifiedBy int, + modified TIMESTAMP, + + 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 SERIAL NOT NULL, + chargeId int, + housingType int, + housingDefinition int, + + startdate timestamp, + releaseCondition int, + + active boolean default true, + objectid ENTITYID, + createdBy int, + created TIMESTAMP, + modifiedBy int, + modified TIMESTAMP, + + CONSTRAINT PK_perDiemFeeDefinition PRIMARY KEY (rowId) +); + +--creates list of all procedures that are billable +CREATE TABLE onprc_billing.clinicalFeeDefinition ( + rowId SERIAL NOT NULL, + procedureId int, + snomed varchar(100), + + active boolean default true, + objectid ENTITYID, + createdBy int, + created TIMESTAMP, + modifiedBy int, + modified TIMESTAMP, + + 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 serial NOT NULL, + procedureId int, + chargeType int, + chargeId int, + + active boolean default true, + objectid ENTITYID, + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + CONSTRAINT PK_procedureFeeDefinition PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_billing.financialContacts ( + rowid serial 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), + + active boolean default true, + objectid ENTITYID, + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + CONSTRAINT PK_financialContacts PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_billing.grants ( + "grant" varchar(100), + investigatorId int, + title varchar(500), + startDate timestamp, + endDate timestamp, + fiscalAuthority int, + + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + CONSTRAINT PK_grants PRIMARY KEY ("grant") +); + +CREATE TABLE onprc_billing.accounts ( + account varchar(100), + "grant" varchar(100), + investigator integer, + startdate timestamp, + enddate timestamp, + externalid varchar(200), + comment varchar(4000), + fiscalAuthority int, + tier integer, + active boolean default true, + + objectid entityid, + createdBy userid, + created timestamp, + modifiedBy userid, + modified timestamp, + + CONSTRAINT PK_accounts PRIMARY KEY (account) +); + +drop table onprc_billing.financialContacts; + +CREATE TABLE onprc_billing.fiscalAuthorities ( + rowid serial NOT NULL, + 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 boolean default true, + objectid ENTITYID, + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + CONSTRAINT pk_fiscalAuthorities PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_billing.projectAccountHistory ( + rowid serial NOT NULL, + project int, + account varchar(200), + startdate timestamp, + enddate timestamp, + objectid entityid, + createdby userid, + created timestamp, + modifiedby userid, + modified timestamp +); + +DROP TABLE onprc_billing.chargableItems; + +CREATE TABLE onprc_billing.chargeableItems ( + rowId SERIAL NOT NULL, + name varchar(200), + shortName varchar(100), + category varchar(200), + comment varchar(4000), + active boolean default true, + + container ENTITYID NOT NULL, + createdBy USERID, + created TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + CONSTRAINT PK_chargeableItems PRIMARY KEY (rowId) +); + +ALTER TABLE onprc_billing.projectAccountHistory ADD CONSTRAINT PK_projectAccountHistory PRIMARY KEY (rowid); + +DROP TABLE onprc_billing.grants; + +CREATE TABLE onprc_billing.grants ( + grantNumber varchar(100), + investigatorId int, + title varchar(500), + startDate timestamp, + endDate timestamp, + fiscalAuthority int, + fundingAgency varchar(200), + grantType varchar(200), + + totalDCBudget double precision, + totalFABudget double precision, + budgetStartDate timestamp, + budgetEndDate timestamp, + + agencyAwardNumber varchar(200), + comment text, + + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + CONSTRAINT PK_grants PRIMARY KEY (grantNumber) +); + +DROP TABLE onprc_billing.accounts; + +CREATE TABLE onprc_billing.grantProjects ( + rowid serial NOT NULL, + 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 timestamp, + awardEndDate timestamp, + budgetStartDate timestamp, + budgetEndDate timestamp, + 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 TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + CONSTRAINT PK_grantProjects PRIMARY KEY (rowid) +); + +CREATE TABLE onprc_billing.iacucFundingSources ( + rowid serial NOT NULL, + protocol varchar(200), + grantNumber varchar(200), + projectNumber varchar(200), + + startdate timestamp, + enddate timestamp, + + container ENTITYID NOT NULL, + createdBy USERID, + created TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + 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 boolean; +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 timestamp; +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 timestamp; + +ALTER Table onprc_billing.invoiceRuns ADD billingPeriodStart timestamp; +ALTER Table onprc_billing.invoiceRuns ADD billingPeriodEnd timestamp; + +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; +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 SET NOT NULL; +SELECT 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 serial NOT NULL, + servicename varchar(200), + chargeType int, + chargeId int, + + active boolean default true, + objectid ENTITYID, + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + CONSTRAINT PK_labworkFeeDefinition PRIMARY KEY (rowId) +); + +ALTER TABLE onprc_billing.invoicedItems ADD servicecenter varchar(200); + +ALTER TABLE onprc_billing.labworkFeeDefinition DROP COLUMN chargeType; +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 timestamp; +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; +ALTER TABLE onprc_billing.invoicedItems ADD transactionNumber varchar(100); + +ALTER TABLE onprc_billing.miscCharges ADD objectid entityid NOT NULL; + +SELECT 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 serial NOT NULL, + userid int, + investigatorId int, + project int, + allData boolean, + + container entityid NOT NULL, + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + 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 serial; +ALTER TABLE onprc_billing.grants ADD container entityid; + +ALTER TABLE onprc_billing.grants DROP CONSTRAINT PK_grants; +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; +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 serial NOT NULL, + 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 timestamp, + modifiedBy USERID, + modified timestamp, + + CONSTRAINT PK_aliases PRIMARY KEY (rowid) +); + +ALTER TABLE onprc_billing.miscCharges ADD debitedaccount varchar(200); +ALTER TABLE onprc_billing.miscCharges RENAME COLUMN creditaccount TO creditedaccount; + +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 boolean DEFAULT false; +UPDATE onprc_billing.chargeableItems SET allowsCustomUnitCost = false; + +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 serial NOT NULL, + chargeid int, + cagetype varchar(100), + cagesize varchar(100), + species varchar(100), + active boolean, + objectid ENTITYID, + createdby int, + created timestamp, + modifiedby int, + modified timestamp, + + 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 serial NOT NULL, + project int, + fa double precision, + remark varchar(4000), + startdate timestamp, + enddate timestamp, + + container entityid, + createdby int, + created timestamp, + modifiedby int, + modified timestamp +); + +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 timestamp; +ALTER TABLE onprc_billing.aliases ADD budgetEndDate timestamp; + +CREATE INDEX IDX_aliases ON onprc_billing.aliases (container, alias); + +ALTER TABLE onprc_billing.invoicedItems DROP CONSTRAINT PK_billedItems; +ALTER TABLE onprc_billing.invoicedItems ALTER COLUMN objectid SET NOT NULL; +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) +); + +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) +); + +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); +UPDATE onprc_billing.creditAccount SET tempaccount = cast(account as varchar(100)); +ALTER TABLE onprc_billing.creditAccount DROP COLUMN account; +ALTER TABLE onprc_billing.creditAccount ADD account varchar(100); +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 serial NOT NULL, + chargeType int, + chargeId int, + + active boolean default true, + objectid ENTITYID, + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + CONSTRAINT PK_bloodDrawFeeDefinition PRIMARY KEY (rowId) +); + +ALTER TABLE onprc_billing.bloodDrawFeeDefinition DROP COLUMN chargetype; +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 boolean, + canRaiseFA boolean, + + createdBy integer, + created timestamp, + modifiedBy integer, + modified timestamp, + + CONSTRAINT PK_aliasTypes PRIMARY KEY (aliasType) +); + +CREATE TABLE onprc_billing.projectMultipliers ( + rowid serial not null, + project integer, + multiplier double precision, + + startdate timestamp, + enddate timestamp, + comment varchar(4000), + + container entityid, + createdBy integer, + created timestamp, + modifiedBy integer, + modified timestamp, + + CONSTRAINT PK_projectMultipliers PRIMARY KEY (rowid) +); + +ALTER TABLE onprc_billing.chargeableItems ADD canRaiseFA boolean; + +ALTER TABLE onprc_billing.miscCharges ADD formSort integer; + +CREATE TABLE onprc_billing.miscChargesType ( + category varchar(100) not null, + + CONSTRAINT PK_miscChargesType PRIMARY KEY (category) +); + +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); +UPDATE onprc_billing.miscCharges SET chargeCategory = chargetype; +UPDATE onprc_billing.miscCharges SET chargetype = null; + +ALTER TABLE onprc_billing.invoicedItems RENAME COLUMN chargetype TO chargeCategory; + +DROP TABLE onprc_billing.bloodDrawFeeDefinition; +DROP TABLE onprc_billing.clinicalFeeDefinition; + +ALTER TABLE onprc_billing.perDiemFeeDefinition ADD canChargeInfants boolean default false; +ALTER TABLE onprc_billing.procedureFeeDefinition ADD assistingStaff VARCHAR(100); + +CREATE TABLE onprc_billing.medicationFeeDefinition ( + rowid serial NOT NULL, + route varchar(100), + chargeId int, + + active boolean default true, + objectid ENTITYID, + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + CONSTRAINT PK_medicationFeeDefinition PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_billing.chargeUnits ( + chargetype varchar(100) NOT NULL, + shownInBlood boolean default false, + shownInLabwork boolean default false, + shownInMedications boolean default false, + shownInProcedures boolean default false, + + active boolean default true, + container entityid, + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + CONSTRAINT PK_chargeUnits PRIMARY KEY (chargetype) +); + +CREATE TABLE onprc_billing.chargeUnitAccounts ( + rowid serial NOT NULL, + chargetype varchar(100), + account varchar(100), + startdate timestamp, + enddate timestamp, + + container entityid, + createdBy int, + created timestamp, + modifiedBy int, + modified timestamp, + + CONSTRAINT PK_chargeUnitAccounts PRIMARY KEY (rowid) +); + +ALTER TABLE onprc_billing.chargeableItems ADD allowBlankId boolean; +UPDATE onprc_billing.chargeableItems SET allowBlankId = false; + +ALTER TABLE onprc_billing.projectMultipliers ADD account varchar(100); +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 +); +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 TIMESTAMP; +ALTER TABLE onprc_billing.procedureFeeDefinition ADD endDate TIMESTAMP; + +ALTER TABLE onprc_billing.labWorkFeeDefinition ADD startDate TIMESTAMP; +ALTER TABLE onprc_billing.labWorkFeeDefinition ADD endDate TIMESTAMP; + +ALTER TABLE onprc_billing.slaPerDiemFeeDefinition ADD startDate TIMESTAMP; +ALTER TABLE onprc_billing.slaPerDiemFeeDefinition ADD endDate TIMESTAMP; + +ALTER TABLE onprc_billing.leaseFeeDefinition ADD startDate TIMESTAMP; +ALTER TABLE onprc_billing.leaseFeeDefinition ADD endDate TIMESTAMP; +ALTER TABLE onprc_billing.chargeableItems ADD startDate TIMESTAMP; +ALTER TABLE onprc_billing.chargeableItems ADD endDate TIMESTAMP; + +ALTER TABLE onprc_billing.perDiemFeeDefinition ADD startDate TIMESTAMP; +ALTER TABLE onprc_billing.perDiemFeeDefinition ADD endDate TIMESTAMP; + +ALTER TABLE onprc_billing.medicationFeeDefinition ADD startDate TIMESTAMP; +ALTER TABLE onprc_billing.medicationFeeDefinition ADD endDate TIMESTAMP; + +/* 12.xxx SQL scripts */ + +-- 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 timestamp, + endDate timestamp, + + createdBy integer, + created timestamp, + modifiedBy integer, + modified timestamp +); + +ALTER TABLE onprc_billing.AnnualInflationRate RENAME TO AnnualRateChange; + +-- Created: 4-26-2017 R.Blasa + +CREATE TABLE onprc_billing.MergeChargtypeUpdates ( + rowid serial NOT NULL, + ProjectName varchar(50) not null, + Protocol varchar(100) not null, + ChargeType varchar(50) not null, + objectid ENTITYID, + startDate timestamp, + endDate timestamp, + + CONSTRAINT PK_MergeType PRIMARY KEY(rowid) +); + +-- Adds table Annual Rate Change to Billing +-- add primary key and identity key +ALTER TABLE onprc_billing.AnnualRateChange Add RowID serial not null; +ALTER TABLE onprc_billing.AnnualRateChange Add CONSTRAINT PK_AnnualRateChange_RowID PRIMARY KEY (RowID); + +-- Adds change inflation rate to 3 position decimal +-- add primary key and identity key +ALTER TABLE onprc_billing.AnnualRateChange ALTER COLUMN InflationRate TYPE Numeric(18,4); + +-- RETAINED BUT DEAD - translated for completeness only; do not wire this up as-is. +-- 1. It reads and writes Rpt_ChargesProjection, which no script in any module creates. +-- 2. Nothing calls it. rateChangeprocess.xml invokes onprc_billing.AnnualRateChangeUpdate, +-- a routine that exists in neither dialect. +-- 3. The SQL Server original ended by returning a result set (SELECT ... FROM Rpt_ChargesProjection +-- ORDER BY chargeid). That is dropped here, since a plpgsql function cannot return a result set +-- without a refcursor or RETURNS TABLE. Reviving this would mean creating the table and +-- reinstating that result set. +-- Contrast onprc_ehr.PrimaSlideBillingReport / PrimaBlockBillingReport, which were dropped from the +-- PostgreSQL translation for the same reason. That omission is silent; this one is recorded here. +CREATE OR REPLACE FUNCTION onprc_billing.AnnualRateChangeProcess() +RETURNS void +LANGUAGE plpgsql +AS $$ +DECLARE + v_Year1 double precision; + v_Year2 double precision; + v_Year3 double precision; + v_Year4 double precision; + v_Year5 double precision; + v_Year6 double precision; + v_Year7 double precision; + v_Year8 double precision; + v_Year9 double precision; + v_Aprate1 double precision := 0; + v_Aprate2 double precision := 0; + v_Aprate3 double precision := 0; + v_Aprate4 double precision := 0; + v_Aprate5 double precision := 0; + v_Aprate6 double precision := 0; + v_Aprate7 double precision := 0; + v_Aprate8 double precision := 0; + v_Aprate9 double precision := 0; + + v_UnitCost double precision := 0.0; + v_nSearchkey int := 0; + v_TempSearchkey int := 0; + v_ChargeId smallint := 0; + v_CurrentBillingYear smallint; + v_Billingyear smallint; +BEGIN + ---- Reset Temp tables + DELETE FROM Rpt_ChargesProjection; + + v_CurrentBillingYear := (EXTRACT(YEAR FROM CURRENT_TIMESTAMP) - 1959)::smallint; + v_Billingyear := v_CurrentBillingYear + 1; + + ---- Begin Processing Data + SELECT rowid INTO v_nSearchkey + FROM onprc_billing.chargeRates + WHERE endDate >= CURRENT_TIMESTAMP + ORDER BY rowid + LIMIT 1; + + --Billing Year Constant + SELECT InflationRate INTO v_Aprate1 FROM onprc_billing.AnnualRateChange WHERE Billingyear = v_BillingYear::varchar; + SELECT InflationRate INTO v_Aprate2 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 1)::varchar; + SELECT InflationRate INTO v_Aprate3 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 2)::varchar; + + IF EXISTS (SELECT 1 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 3)::varchar) THEN + SELECT InflationRate INTO v_Aprate4 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 3)::varchar; + END IF; + + IF EXISTS (SELECT 1 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 4)::varchar) THEN + SELECT InflationRate INTO v_Aprate5 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 4)::varchar; + END IF; + + IF EXISTS (SELECT 1 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 5)::varchar) THEN + SELECT InflationRate INTO v_Aprate6 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 5)::varchar; + END IF; + + IF EXISTS (SELECT 1 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 6)::varchar) THEN + SELECT InflationRate INTO v_Aprate7 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 6)::varchar; + END IF; + + IF EXISTS (SELECT 1 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 7)::varchar) THEN + SELECT InflationRate INTO v_Aprate8 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 7)::varchar; + END IF; + + IF EXISTS (SELECT 1 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 8)::varchar) THEN + SELECT InflationRate INTO v_Aprate9 FROM onprc_billing.AnnualRateChange WHERE Billingyear = (v_BillingYear + 8)::varchar; + END IF; + + WHILE v_TempSearchKey < v_nSearchkey LOOP + v_Year1 := 0.0; + v_Year2 := 0.0; + v_Year3 := 0.0; + v_Year4 := 0.0; + v_Year5 := 0.0; + v_Year6 := 0.0; + v_Year7 := 0.0; + v_Year8 := 0.0; + v_Year9 := 0.0; + v_UnitCost := 0.0; + v_ChargeId := 0; + + IF EXISTS(SELECT 1 FROM onprc_billing.chargeRates WHERE endDate >= CURRENT_TIMESTAMP AND rowid = v_nSearchkey) THEN + SELECT unitcost, chargeid INTO v_UnitCost, v_ChargeId + FROM onprc_billing.chargeRates + WHERE endDate >= CURRENT_TIMESTAMP AND rowid = v_nSearchkey + ORDER BY rowid + LIMIT 1; + + v_Year1 := v_Aprate1 * v_UnitCost; + v_Year2 := v_Year1 * v_Aprate2; + v_Year3 := v_Year2 * v_Aprate3; + v_Year4 := v_Year3 * v_Aprate4; + v_Year5 := v_Year4 * v_Aprate5; + v_Year6 := v_Year5 * v_Aprate6; + v_Year7 := v_Year6 * v_Aprate7; + v_Year8 := v_Year7 * v_Aprate8; + v_Year9 := v_Year8 * v_Aprate9; + + INSERT INTO Rpt_ChargesProjection + VALUES ( + v_ChargeId, + v_UnitCost, + v_Year1, + v_Year2, + v_Year3, + v_Year4, + v_Year5, + v_Year6, + v_Year7, + v_Year8, + v_Aprate1, + v_Aprate2, + v_Aprate3, + v_Aprate4, + v_Aprate5, + v_Aprate6, + v_Aprate7, + v_Aprate8, + v_Aprate9, + v_nSearchkey, + CURRENT_TIMESTAMP + ); + END IF; + + v_TempSearchKey := v_nSearchkey; + + SELECT rowid INTO v_nSearchkey + FROM onprc_billing.chargeRates + WHERE endDate >= CURRENT_TIMESTAMP AND rowid > v_nSearchkey + ORDER BY rowid + LIMIT 1; + + IF NOT FOUND THEN + EXIT; + END IF; + END LOOP; +END; +$$; + +/* 20.xxx SQL scripts */ + +-- 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 +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'COMMENTS'); +ALTER TABLE onprc_billing.aliases ADD COMMENTS VarChar(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'dateDisabled'); +ALTER TABLE onprc_billing.aliases ADD dateDisabled TIMESTAMP Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'PPQNumber'); +ALTER TABLE onprc_billing.aliases ADD PPQNumber VARCHAR(25) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'PPQDate'); +ALTER TABLE onprc_billing.aliases ADD PPQDate TIMESTAMP Null; + +SELECT core.fn_dropifexists('ogaSynch', 'onprc_billing', 'TABLE', NULL); + +CREATE TABLE onprc_billing.ogasynch ( + lastIndexed timestamp NULL, + modifiedBy int NULL, + container ENTITYID NOT NULL, + modified timestamp NULL, + created timestamp NULL, + entityId ENTITYID NOT NULL, + createdBy int NULL, + "ADFM EMP NUM" int NULL, + "ADFM FULL NAME" varchar(4000) NULL, + "ADFM LAST NAME" varchar(4000) NULL, + "ADFM FIRST NAME" varchar(4000) NULL, + "PI EMP NUM" int NULL, + "PI FULL NAME" varchar(4000) NULL, + "PI LAST NAME" varchar(4000) NULL, + "PI FIRST NAME" varchar(4000) NULL, + "PDFM EMP NUM" int NULL, + "PDFM FULL NAME" varchar(4000) NULL, + "PDFM LAST NAME" varchar(4000) NULL, + "PDFM FIRST NAME" varchar(4000) NULL, + "AGENCY AWARD NUMBER" varchar(4000) NULL, + "OGA AWARD NUMBER" varchar(4000) NULL, + "OGA AWARD TYPE" varchar(4000) NULL, + "OGA PROJECT NUMBER" varchar(4000) NULL, + "ALIAS" int NULL, + "ALIAS ENABLED FLAG" boolean NULL, + "ALIAS ENABLED FLAG_MVIndicator" varchar(50) NULL, + "PROJECT DESCRIPTION" varchar(4000) NULL, + "APPLICATION TYPE" int NULL, + "ACTIVITY TYPE" varchar(4000) NULL, + "AWARD NUMBER" varchar(4000) NULL, + "AWARD SUFFIX" varchar(4000) NULL, + "ORG" varchar(4000) NULL, + "CURRENT BUDGET START DATE" timestamp NULL, + "CURRENT BUDGET END DATE" timestamp NULL, + "PROJECT TITLE" varchar(4000) NULL, + "PPQ CODE" varchar(4000) NULL, + "PPQ DATE" timestamp NULL, + "IACUC NUMBER" varchar(4000) NULL, + "AWARD STATUS" varchar(4000) NULL, + "PROJECT STATUS" varchar(4000) NULL, + "AWARD ID" int NULL, + "PROJECT ID" int NULL, + "BURDEN SCHEDULE" varchar(4000) NULL, + "BURDEN RATE" double precision NULL, + "faRate" double precision NULL, + "Key" serial NOT NULL +); + +-- 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 +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'); +ALTER TABLE onprc_billing.aliases ADD ApplicationType VarChar(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ApplicationTypeDescription'); +ALTER TABLE onprc_billing.aliases ADD ApplicationTypeDescription VarChar(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'AwardStatus'); +ALTER TABLE onprc_billing.aliases ADD AwardStatus VARCHAR(100) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'AwardID'); +ALTER TABLE onprc_billing.aliases ADD AwardID VARCHAR(100) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'); +ALTER TABLE onprc_billing.aliases ADD ApplicationType VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ProjectID'); +ALTER TABLE onprc_billing.aliases ADD ProjectID VARCHAR(100) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ActivityType'); +ALTER TABLE onprc_billing.aliases ADD ActivityType VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'AwardNumber'); +ALTER TABLE onprc_billing.aliases ADD AwardNumber VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'AwardSuffix'); +ALTER TABLE onprc_billing.aliases ADD AwardSuffix VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'Org'); +ALTER TABLE onprc_billing.aliases ADD Org VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ADFMEmpNum'); +ALTER TABLE onprc_billing.aliases ADD ADFMEmpNum VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ADFMFullName'); +ALTER TABLE onprc_billing.aliases ADD ADFMFullName VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ActivityTypeDescription'); +ALTER TABLE onprc_billing.aliases ADD ActivityTypeDescription VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'FundingSourceNumber'); +ALTER TABLE onprc_billing.aliases ADD FundingSourceNumber VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'FundingSourceName'); +ALTER TABLE onprc_billing.aliases ADD FundingSourceName VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'Org'); +ALTER TABLE onprc_billing.aliases ADD Org VARCHAR(255) Null; + +CREATE OR REPLACE FUNCTION onprc_billing.AliasCleanup202004() +RETURNS void +LANGUAGE plpgsql +AS $$ +BEGIN + --Handles active non OGA Aliases + UPDATE onprc_billing.aliases a + SET projectStatus = 'Active', comments = 'In Use - Non ONPRC Alias', category = 'OHSU GL' + FROM onprc_billing.projectAccountHistory p + WHERE p.account = a.alias + AND p.enddate >= CURRENT_TIMESTAMP AND a.alias NOT LIKE '9%'; + + -- updates the alias dataset setting end date and comment for disabled aliases + UPDATE onprc_billing.aliases a + SET dateDisabled = '2020-04-01', Comments = 'Alias Disabled' + WHERE aliasEnabled = 'N' OR aliasEnabled = 'n'; + + UPDATE onprc_billing.aliases a1 + SET projectStatus = 'Non Active GL', aliasEnabled = 'n', datedisabled = CURRENT_TIMESTAMP, comments = 'GL Alias Not Active entered Previously' + WHERE a1.alias NOT LIKE '9%' AND (lower(a1.comments) != lower('In Use - Non ONPRC Alias') OR a1.comments IS NULL); + + UPDATE onprc_billing.aliases a2 + SET dateDisabled = CURRENT_TIMESTAMP, comments = 'Expired Alias', aliasEnabled = 'n' + WHERE a2.budgetEndDate <= CURRENT_TIMESTAMP; + + UPDATE onprc_billing.aliases a4 + SET dateDisabled = CURRENT_TIMESTAMP, comments = 'Grant Closed', projectStatus = 'Grant Closed', aliasEnabled = 'N' + FROM onprc_billing.ogasynch s + WHERE CAST(a4.alias AS varchar(50)) = CAST(s."ALIAS" AS varchar(50)) + AND a4.dateDisabled IS NULL AND lower(a4.projectstatus) IN (lower('Archived'), lower('Closed'), lower('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 + ); +END; +$$; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'); +ALTER TABLE onprc_billing.aliases ADD ApplicationType VarChar(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ApplicationTypeDescription'); +ALTER TABLE onprc_billing.aliases ADD ApplicationTypeDescription VarChar(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'AwardStatus'); +ALTER TABLE onprc_billing.aliases ADD AwardStatus VARCHAR(100) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'AwardID'); +ALTER TABLE onprc_billing.aliases ADD AwardID VARCHAR(100) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'); +ALTER TABLE onprc_billing.aliases ADD ApplicationType VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ProjectID'); +ALTER TABLE onprc_billing.aliases ADD ProjectID VARCHAR(100) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ActivityType'); +ALTER TABLE onprc_billing.aliases ADD ActivityType VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'AwardNumber'); +ALTER TABLE onprc_billing.aliases ADD AwardNumber VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'AwardSuffix'); +ALTER TABLE onprc_billing.aliases ADD AwardSuffix VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'Org'); +ALTER TABLE onprc_billing.aliases ADD Org VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ADFMEmpNum'); +ALTER TABLE onprc_billing.aliases ADD ADFMEmpNum VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ADFMFullName'); +ALTER TABLE onprc_billing.aliases ADD ADFMFullName VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'ActivityTypeDescription'); +ALTER TABLE onprc_billing.aliases ADD ActivityTypeDescription VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'FundingSourceNumber'); +ALTER TABLE onprc_billing.aliases ADD FundingSourceNumber VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'FundingSourceName'); +ALTER TABLE onprc_billing.aliases ADD FundingSourceName VARCHAR(255) Null; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'Org'); +ALTER TABLE onprc_billing.aliases ADD Org VARCHAR(255) Null; + +DROP FUNCTION IF EXISTS onprc_billing.OGA_RemoveRecords(); + +CREATE OR REPLACE FUNCTION onprc_billing.OGA_RemoveRecords() +RETURNS void +LANGUAGE plpgsql +AS $$ +BEGIN + DELETE FROM onprc_billing.aliases + WHERE lower(category) != lower('OHSU GL'); +END; +$$; + +DROP FUNCTION IF EXISTS onprc_ehr.RateCalc(varchar, float8, float8, date, float8); + +CREATE OR REPLACE FUNCTION onprc_ehr.RateCalc +( + v_alias varchar(20), + v_chargeId float8, + v_project float8, + v_startDate date, + v_baseSubsidyVal float8 +) +RETURNS float8 +LANGUAGE plpgsql +AS $$ +DECLARE + unitCostVal float8; + projectExemption float8; + projectMultipler float8; + unitCost float8; + NonOGAAlias varchar(20); + blankAliasType varchar(20); + baseSubsidy float8; + subsidy float8; + faRate float8; + removeSubsidy smallint; + aliasRaiseFA smallint; + chargeRaiseFA smallint; +BEGIN + v_baseSubsidyVal := .47; + basesubsidy := .47; + unitCost := 1000; + subsidy := v_baseSubsidyVal; + + -- Each lookup below is a scalar subquery, matching the SQL Server original's "SET @x = (SELECT ...)". + -- Both dialects yield NULL when nothing matches and raise an error when more than one row matches. + -- Do not substitute LIMIT 1: overlapping date ranges would then silently pick an arbitrary rate. + projectExemption := ( + SELECT cr.unitcost + FROM onprc_billing.chargeRateExemptions cr + WHERE cr.chargeId = v_chargeId::integer + AND cr.project = v_project::integer + AND cr.startDate < v_startDate + AND ((v_startDate <= cr.endDate) OR (cr.enddate IS NULL))); + + projectMultipler := ( + SELECT pm.multiplier + FROM onprc_billing.projectMultipliers pm + WHERE pm.account = v_alias + AND pm.startdate <= v_startDate + AND ((pm.enddate >= v_startDate) OR (pm.enddate IS NULL))); + + NonOGAAlias := ( + SELECT a.category + FROM onprc_billing.aliases a + WHERE a.alias = v_alias + AND (a.budgetStartDate < v_startDate AND a.budgetEndDate > v_startDate)); + + blankAliasType := ( + SELECT a.aliasType + FROM onprc_billing.aliases a + WHERE a.alias = v_alias + AND (a.budgetStartDate < v_startDate AND a.budgetEndDate > v_startDate)); + + removeSubsidy := ( + SELECT CASE WHEN t.removeSubsidy = true THEN 1 ELSE 0 END + FROM onprc_billing.aliases a + JOIN onprc_billing.aliasTypes t ON a.aliasType = t.aliasType + WHERE a.alias = v_alias + AND (a.budgetStartDate < v_startDate AND a.budgetEndDate > v_startDate)); + + chargeRaiseFA := ( + SELECT CASE WHEN c.canRaiseFA = true THEN 1 ELSE 0 END + FROM onprc_billing.chargeableItems c + JOIN onprc_billing.chargeRates cr ON c.rowId = cr.chargeId + WHERE cr.chargeId = v_chargeId::integer + AND (cr.StartDate < v_startDate AND cr.EndDate > v_startDate)); + + aliasRaiseFA := ( + SELECT CASE WHEN t.canRaiseFA = true THEN 1 ELSE 0 END + FROM onprc_billing.aliases a + JOIN onprc_billing.aliasTypes t ON a.aliasType = t.aliasType + WHERE a.alias = v_alias + AND (a.budgetStartDate < v_startDate AND a.budgetEndDate > v_startDate)); + + faRate := ( + SELECT a.faRate + FROM onprc_billing.aliases a + WHERE a.alias = v_alias + AND (a.budgetStartDate < v_startDate AND a.budgetEndDate > v_startDate)); + + unitCost := ( + SELECT r.unitcost + FROM onprc_billing.chargeRates r + WHERE r.chargeID = v_chargeId::integer + AND r.startDate <= v_startDate + AND ((r.enddate >= v_startDate) OR r.enddate IS NULL)); + + unitCostVal := CASE + WHEN projectExemption IS NOT NULL THEN projectExemption + WHEN projectMultipler IS NOT NULL THEN projectMultipler * unitCost + WHEN unitCost IS NULL THEN NULL + WHEN NonOGAAlias IS NOT NULL AND lower(NonOGAAlias) != lower('OGA') THEN unitCost + 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 unitCostVal; +END; +$$; + +DROP FUNCTION IF EXISTS onprc_billing.ClearOGASync(); + +CREATE OR REPLACE FUNCTION onprc_billing.ClearOGASync() +RETURNS void +LANGUAGE plpgsql +AS $$ +BEGIN + DELETE FROM onprc_billing.ogasynch; +END; +$$; + +/* 22.xxx SQL scripts */ + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'Originating Agency Award Number'); +ALTER TABLE onprc_billing.aliases ADD OriginatingAgencyAwardNum VarChar(255) Null; +ALTER TABLE onprc_billing.ogaSynch ADD ORIGINATING_AGENCY_AWARD_NUM VarChar(255) Null; + +--20220406 update of SP for insert +DROP FUNCTION IF EXISTS onprc_billing.oga_InsertRecords(); + +CREATE OR REPLACE FUNCTION onprc_billing.oga_InsertRecords() +RETURNS void +LANGUAGE plpgsql +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, + OriginatingAgencyAwardNum + ) + SELECT + CAST(o."ALIAS" AS varchar(200)), + CASE + WHEN o."ALIAS ENABLED FLAG" = true THEN 'y' + WHEN o."ALIAS ENABLED FLAG" = false THEN 'n' + ELSE NULL + END AS AliasEnabled, + o."OGA PROJECT NUMBER", + o."OGA AWARD NUMBER", + o."AGENCY AWARD NUMBER", + i.rowId, + o."PI FULL NAME", + f.rowid, + '0F8BB08E-E4BF-102F-B89B-5107380A5B61'::entityid, + 1003, + CURRENT_TIMESTAMP, + 'OGA', + o."faRate", + o."BURDEN SCHEDULE", + o."CURRENT BUDGET START DATE", + o."CURRENT BUDGET END DATE", + o."PROJECT TITLE", + o."PROJECT DESCRIPTION", + o."PROJECT STATUS", + o."OGA AWARD TYPE", + 'ENTERED BY ISE', + o."PPQ CODE", + o."PPQ DATE", + o."AWARD STATUS", + CAST(o."AWARD ID" AS varchar(100)), + CAST(o."APPLICATION TYPE" AS varchar(255)), + CAST(o."PROJECT ID" AS varchar(100)), + o."OGA AWARD TYPE", + o."AWARD NUMBER", + o."AWARD SUFFIX", + CAST(o."ADFM EMP NUM" AS varchar(255)), + o."ADFM FULL NAME", + o."ORG", + o.ORIGINATING_AGENCY_AWARD_NUM + FROM onprc_billing.ogasynch o + LEFT OUTER JOIN onprc_ehr.investigators i ON CAST(o."PI EMP NUM" AS varchar(100)) = i.employeeid AND i.datedisabled IS NULL + LEFT OUTER JOIN onprc_billing.fiscalAuthorities f ON f.employeeId = CAST(o."PDFM EMP NUM" AS varchar(100)) AND f.active = true; +END; +$$; + +SELECT core.fn_dropifexists('aliases', 'onprc_billing', 'COLUMN', 'OriginatingAgencyAwardNum'); +SELECT core.fn_dropifexists('ogaSynch', 'onprc_billing', 'COLUMN', 'ORIGINATING_AGENCY_AWARD_NUM'); +ALTER TABLE onprc_billing.aliases ADD OriginatingAgencyAwardNum VarChar(255) Null; +ALTER TABLE onprc_billing.ogaSynch ADD ORIGINATING_AGENCY_AWARD_NUM VarChar(255) Null; + +/* 23.xxx SQL scripts */ + +DROP FUNCTION IF EXISTS onprc_billing.UpdateClinPathEndDate(); + +CREATE OR REPLACE FUNCTION onprc_billing.UpdateClinPathEndDate() +RETURNS void +LANGUAGE plpgsql +AS $$ +BEGIN + UPDATE studyDataset.c6d199_clinpathruns + SET datefinalized = date + WHERE dateFinalized IS NULL AND date > '2023-05-01' AND qcstate = 18; +END; +$$; + +/*Corrected to remove sql script not related to this module.*/ +SELECT core.fn_dropifexists('annualinflationrate', 'onprc_billing', 'table', NULL); diff --git a/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-25.002-25.003.sql b/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-25.002-25.003.sql new file mode 100644 index 000000000..0a7bf4f25 --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-25.002-25.003.sql @@ -0,0 +1,7 @@ +SELECT core.fn_dropifexists('ogaSynch', 'onprc_billing', 'COLUMN', 'OGA_AWARD_START_DATE'); +SELECT core.fn_dropifexists('ogaSynch', 'onprc_billing', 'COLUMN', 'OGA_AWARD_END_DATE'); +SELECT core.fn_dropifexists('ogaSynch', 'onprc_billing', 'COLUMN', 'IndirectRate'); + +ALTER TABLE onprc_billing.ogaSynch ADD OGA_AWARD_START_DATE DATE NULL; +ALTER TABLE onprc_billing.ogaSynch ADD OGA_AWARD_END_DATE DATE NULL; +ALTER TABLE onprc_billing.ogaSynch ADD IndirectRate DOUBLE PRECISION NULL; diff --git a/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-25.004-25.005.sql b/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-25.004-25.005.sql new file mode 100644 index 000000000..f694ebf2c --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-25.004-25.005.sql @@ -0,0 +1,19 @@ +-- Contents of onprc_billing25.001-25.002.sql + +--cREATED 4/7/2025 +--gjones +--NEW Data Set to Select Ciorrect Subsidy for Unit Cost Calculations +--changes name to Indirect +-- +CREATE TABLE onprc_billing.IndirectRates ( + rowId SERIAL NOT NULL, + Title varchar(50) NULL, + IndirectRate double precision, + startDate timestamp, + endDate timestamp, + + createdBy integer, + created timestamp, + modifiedBy integer, + modified timestamp +); diff --git a/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-25.005-25.006.sql b/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-25.005-25.006.sql new file mode 100644 index 000000000..50db3a670 --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/postgresql/onprc_billing-25.005-25.006.sql @@ -0,0 +1,4 @@ +--This update allows the endDate field to be NULL +--Revised 2025-06-30 +ALTER TABLE onprc_billing.IndirectRates + ALTER COLUMN endDate DROP NOT NULL; 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 deleted file mode 100644 index cc8c1ab83..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-0.00-12.372.sql +++ /dev/null @@ -1,944 +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 -; - ---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-0.000-25.000.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-0.000-25.000.sql new file mode 100644 index 000000000..04af7abdd --- /dev/null +++ b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-0.000-25.000.sql @@ -0,0 +1,2570 @@ +/* + * 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; + +/* 12.xxx SQL scripts */ + +-- 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 + +GO + +/* 20.xxx SQL scripts */ + +-- 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 +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'COMMENTS'; +GO +ALTER TABLE onprc_billing.aliases ADD [COMMENTS] VarChar(255) Null; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'dateDisabled'; +GO +ALTER TABLE onprc_billing.aliases ADD [dateDisabled] DATETIME Null; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'PPQNumber'; +GO +ALTER TABLE onprc_billing.aliases ADD [PPQNumber] VARCHAR(25) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'PPQDate'; +GO +ALTER TABLE onprc_billing.aliases ADD [PPQDate] DATETIME Null; + +EXEC core.fn_dropifexists 'ogaSynch','onprc_billing','TABLE'; +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 + +-- 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 +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'; +GO +ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VarChar(255) Null; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationTypeDescription'; +GO +ALTER TABLE onprc_billing.aliases ADD [ApplicationTypeDescription] VarChar(255) Null; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardStatus'; +GO +ALTER TABLE onprc_billing.aliases ADD [AwardStatus] VARCHAR(100) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardID'; +GO +ALTER TABLE onprc_billing.aliases ADD [AwardID] VARCHAR(100) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'; +GO +ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VARCHAR(255) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ProjectID'; +GO +ALTER TABLE onprc_billing.aliases ADD [ProjectID] VARCHAR(100) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ActivityType'; +GO +ALTER TABLE onprc_billing.aliases ADD [ActivityType] VARCHAR(255) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardNumber'; +GO +ALTER TABLE onprc_billing.aliases ADD [AwardNumber] VARCHAR(255) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardSuffix'; +GO +ALTER TABLE onprc_billing.aliases ADD [AwardSuffix] VARCHAR(255) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'Org'; +GO +ALTER TABLE onprc_billing.aliases ADD [Org] VARCHAR(255) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ADFMEmpNum'; +GO +ALTER TABLE onprc_billing.aliases ADD [ADFMEmpNum] VARCHAR(255) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ADFMFullName'; +GO +ALTER TABLE onprc_billing.aliases ADD [ADFMFullName] VARCHAR(255) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ActivityTypeDescription'; +GO +ALTER TABLE onprc_billing.aliases ADD [ActivityTypeDescription] VARCHAR(255) NUll; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'FundingSourceNumber'; +GO +ALTER TABLE onprc_billing.aliases ADD [FUndingSourceNumber] VARCHAR(255) NUll + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'FundingSourceName'; +GO +ALTER TABLE onprc_billing.aliases ADD [FUndingSourceName] VARCHAR(255) NUll + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'Org'; +GO +ALTER TABLE onprc_billing.aliases ADD [Org] VARCHAR(255) NUll + +--Adding additional fields to OGA Synch + +-- ================================================ +-- 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 + +-- 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 +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'; +GO +ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VarChar(255) Null; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationTypeDescription'; +GO +ALTER TABLE onprc_billing.aliases ADD [ApplicationTypeDescription] VarChar(255) Null; + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardStatus'; +GO +ALTER TABLE onprc_billing.aliases ADD [AwardStatus] VARCHAR(100) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardID'; +GO +ALTER TABLE onprc_billing.aliases ADD [AwardID] VARCHAR(100) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'; +GO +ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VARCHAR(255) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ProjectID'; +GO +ALTER TABLE onprc_billing.aliases ADD [ProjectID] VARCHAR(100) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ActivityType'; +GO +ALTER TABLE onprc_billing.aliases ADD [ActivityType] VARCHAR(255) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardNumber'; +GO +ALTER TABLE onprc_billing.aliases ADD [AwardNumber] VARCHAR(255) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardSuffix'; +GO +ALTER TABLE onprc_billing.aliases ADD [AwardSuffix] VARCHAR(255) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'Org'; +GO +ALTER TABLE onprc_billing.aliases ADD [Org] VARCHAR(255) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ADFMEmpNum'; +GO +ALTER TABLE onprc_billing.aliases ADD [ADFMEmpNum] VARCHAR(255) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ADFMFullName'; +GO +ALTER TABLE onprc_billing.aliases ADD [ADFMFullName] VARCHAR(255) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ActivityTypeDescription'; +GO +ALTER TABLE onprc_billing.aliases ADD [ActivityTypeDescription] VARCHAR(255) NUll; +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'FundingSourceNumber'; +GO +ALTER TABLE onprc_billing.aliases ADD [FUndingSourceNumber] VARCHAR(255) NUll +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'FundingSourceName'; +GO +ALTER TABLE onprc_billing.aliases ADD [FUndingSourceName] VARCHAR(255) NUll +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'Org'; +GO +ALTER TABLE onprc_billing.aliases ADD [Org] VARCHAR(255) NUll + +--Adding additional fields to OGA Synch + +/****** 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 ******/ +EXEC core.fn_dropifexists 'OGA_RemoveRecords', 'onprc_billing', 'PROCEDURE' +GO + +CREATE PROCEDURE [onprc_billing].[OGA_RemoveRecords] + AS + BEGIN + + Delete from onprc_billing.aliases + where category != 'OHSU GL' + + + + END + +GO + +/****** Object: StoredProcedure [onprc_billing].[oga_InsertRecords] Script Date: 5/18/2020 10:35:50 AM ******/ +EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' +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 + +GO + +/****** 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 + +GO + +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 + +GO + +/****** Object: StoredProcedure [onprc_billing].[OGA_RemoveRecords] Script Date: 10/15/2020 9:30:00 AM ******/ + +EXEC core.fn_dropifexists 'ClearOGASync', 'onprc_billing', 'PROCEDURE' +GO + +CREATE PROCEDURE [onprc_billing].[ClearOGASync] +AS +BEGIN + +Delete from onprc_billing.ogasynch + +END + +GO + +/****** Object: StoredProcedure [onprc_billing].[oga_InsertRecords] + Script Date: 5/18/2020 10:35:50 AM +Update 2020-11-25 jonesga to change source of fa rate from burden rate to cast value + ******/ +EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' +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' + ,[farate] + ,[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 + +GO + +/****** Object: StoredProcedure [onprc_billing].[oga_InsertRecords] + Script Date: 5/18/2020 10:35:50 AM +Update 2020-11-25 jonesga to change source of fa rate from burden rate to cast value + ******/ +EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' +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], + Case + when [ALIAS ENABLED FLAG] = 1 then 'y' + when [ALIAS ENABLED FLAG] = 0 then 'n' + End as AliasEnabled + -- ,[ALIAS ENABLED FLAG] + ,[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' + ,[farate] + ,[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 +GO + +/****** Object: StoredProcedure [onprc_billing].[oga_InsertRecords] Script Date: 12/2/2020 12:18:09 PM ******/ +EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' +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], + Case + when [ALIAS ENABLED FLAG] = 1 then 'y' + when [ALIAS ENABLED FLAG] = 0 then 'n' + End as AliasEnabled + + ,[OGA PROJECT NUMBER] + ,[OGA AWARD NUMBER] + ,[AGENCY AWARD NUMBER] + ,i.rowId + --End as [PI EMP NUM] + ,[PI FULL NAME] + ,f.rowid + --,[PDFM EMP NUM] + ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' + ,1003 + ,GetDate() + ,'OGA' + ,[farate] + ,[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] o + left outer join [onprc_ehr].investigators i on o.[PI EMP NUM] = i.employeeid + left outer join onprc_billing.fiscalAuthorities f on f.employeeId = o.[PDFM EMP NUM] +END +GO + +EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' +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], + Case + when [ALIAS ENABLED FLAG] = 1 then 'y' + when [ALIAS ENABLED FLAG] = 0 then 'n' + End as AliasEnabled + + ,[OGA PROJECT NUMBER] + ,[OGA AWARD NUMBER] + ,[AGENCY AWARD NUMBER] + ,i.rowId + --End as [PI EMP NUM] + ,[PI FULL NAME] + ,f.rowid + --,[PDFM EMP NUM] + ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' + ,1003 + ,GetDate() + ,'OGA' + ,[farate] + ,[BURDEN SCHEDULE] + ,[CURRENT BUDGET START DATE] + ,[CURRENT BUDGET END DATE] + ,[PROJECT TITLE] + ,[PROJECT DESCRIPTION] + ,[PROJECT STATUS] + ,[OGA AWARD 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] o + left outer join [onprc_ehr].investigators i on o.[PI EMP NUM] = i.employeeid + left outer join onprc_billing.fiscalAuthorities f on f.employeeId = o.[PDFM EMP NUM] +END +GO + +EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' +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], + Case + when [ALIAS ENABLED FLAG] = 1 then 'y' + when [ALIAS ENABLED FLAG] = 0 then 'n' + End as AliasEnabled + + ,[OGA PROJECT NUMBER] + ,[OGA AWARD NUMBER] + ,[AGENCY AWARD NUMBER] + ,i.rowId + --End as [PI EMP NUM] + ,[PI FULL NAME] + ,f.rowid + --,[PDFM EMP NUM] + ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' + ,1003 + ,GetDate() + ,'OGA' + ,[farate] + ,[BURDEN SCHEDULE] + ,[CURRENT BUDGET START DATE] + ,[CURRENT BUDGET END DATE] + ,[PROJECT TITLE] + ,[PROJECT DESCRIPTION] + ,[PROJECT STATUS] + ,[OGA AWARD 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] o + left outer join [onprc_ehr].investigators i on o.[PI EMP NUM] = i.employeeid and i.datedisabled is Null + left outer join onprc_billing.fiscalAuthorities f on f.employeeId = o.[PDFM EMP NUM] and f.active = 'true'; + +END +GO + +EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' +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], + Case + when [ALIAS ENABLED FLAG] = 1 then 'y' + when [ALIAS ENABLED FLAG] = 0 then 'n' + End as AliasEnabled + + ,[OGA PROJECT NUMBER] + ,[OGA AWARD NUMBER] + ,[AGENCY AWARD NUMBER] + ,i.rowId + --End as [PI EMP NUM] + ,[PI FULL NAME] + ,f.rowid + --,[PDFM EMP NUM] + ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' + ,1003 + ,GetDate() + ,'OGA' + ,[farate] + ,[BURDEN SCHEDULE] + ,[CURRENT BUDGET START DATE] + ,[CURRENT BUDGET END DATE] + ,[PROJECT TITLE] + ,[PROJECT DESCRIPTION] + ,[PROJECT STATUS] + ,[OGA AWARD 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] o + left outer join [onprc_ehr].investigators i on o.[PI EMP NUM] = i.employeeid and i.datedisabled is Null + left outer join onprc_billing.fiscalAuthorities f on f.employeeId = o.[PDFM EMP NUM] and f.active = 'true'; + +END +GO + +/* 22.xxx SQL scripts */ + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'Originating Agency Award Number'; +GO +ALTER TABLE onprc_billing.aliases ADD [OriginatingAgencyAwardNum] VarChar(255) Null; +GO +ALTER TABLE onprc_billing.ogaSynch ADD [ORIGINATING_AGENCY_AWARD_NUM] VarChar(255) Null; + +--20220406 update of SP for insert +EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' +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] +,[OriginatingAgencyAwardNum] +) +SELECT + [Alias], + Case + when [ALIAS ENABLED FLAG] = 1 then 'y' + when [ALIAS ENABLED FLAG] = 0 then 'n' + End as AliasEnabled + + ,[OGA PROJECT NUMBER] + ,[OGA AWARD NUMBER] + ,[AGENCY AWARD NUMBER] + ,i.rowId + --End as [PI EMP NUM] + ,[PI FULL NAME] + ,f.rowid + --,[PDFM EMP NUM] + ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' + ,1003 + ,GetDate() + ,'OGA' + ,[farate] + ,[BURDEN SCHEDULE] + ,[CURRENT BUDGET START DATE] + ,[CURRENT BUDGET END DATE] + ,[PROJECT TITLE] + ,[PROJECT DESCRIPTION] + ,[PROJECT STATUS] + ,[OGA AWARD 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] + ,[ORIGINATING_AGENCY_AWARD_NUM] + From [onprc_billing].[ogasynch] o + left outer join [onprc_ehr].investigators i on o.[PI EMP NUM] = i.employeeid and i.datedisabled is Null + left outer join onprc_billing.fiscalAuthorities f on f.employeeId = o.[PDFM EMP NUM] and f.active = 'true'; + +END +GO + +EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'OriginatingAgencyAwardNum'; +GO +EXEC core.fn_dropifexists 'ogaSynch', 'onprc_billing', 'COLUMN', 'ORIGINATING_AGENCY_AWARD_NUM'; +GO +ALTER TABLE onprc_billing.aliases ADD [OriginatingAgencyAwardNum] VarChar(255) Null; +GO +ALTER TABLE onprc_billing.ogaSynch ADD [ORIGINATING_AGENCY_AWARD_NUM] VarChar(255) Null; + +/* 23.xxx SQL scripts */ + +IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'UpdateClinPathEndDate') +DROP PROCEDURE UpdateClinPathEndDate + GO +CREATE PROCEDURE onprc_billing.UpdateClinPathEndDate + + AS +BEGIN + --Updates end Date for ClinPath when complete but no dateUpdate [Labkey_uat].[studyDataset].[c6d199_clinpathruns] + --update todya 8/16/2023 +Update [studyDataset].[c6d199_clinpathruns] +set datefinalized = date +where dateFinalized is null and date > '5/1/2023' and qcstate = 18 + + + + + +END +GO + +/*Corrected to remove sql script not related to this module.*/ +EXEC core.fn_dropifexists 'annualinflationrate','onprc_billing','table',Null \ 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 deleted file mode 100644 index e41fecc44..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-12.372-18.10.sql +++ /dev/null @@ -1,345 +0,0 @@ --- 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 - -GO 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 deleted file mode 100644 index c6026dfb2..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.101-20.102.sql +++ /dev/null @@ -1,18 +0,0 @@ --- 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 -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'COMMENTS'; -GO -ALTER TABLE onprc_billing.aliases ADD [COMMENTS] VarChar(255) Null; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'dateDisabled'; -GO -ALTER TABLE onprc_billing.aliases ADD [dateDisabled] DATETIME Null; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'PPQNumber'; -GO -ALTER TABLE onprc_billing.aliases ADD [PPQNumber] VARCHAR(25) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'PPQDate'; -GO -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 deleted file mode 100644 index fed65f82d..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.102-20.103.sql +++ /dev/null @@ -1,52 +0,0 @@ -EXEC core.fn_dropifexists 'ogaSynch','onprc_billing','TABLE'; -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 deleted file mode 100644 index ad5b0e328..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.104-20.105.sql +++ /dev/null @@ -1,68 +0,0 @@ --- 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 -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'; -GO -ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VarChar(255) Null; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationTypeDescription'; -GO -ALTER TABLE onprc_billing.aliases ADD [ApplicationTypeDescription] VarChar(255) Null; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardStatus'; -GO -ALTER TABLE onprc_billing.aliases ADD [AwardStatus] VARCHAR(100) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardID'; -GO -ALTER TABLE onprc_billing.aliases ADD [AwardID] VARCHAR(100) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'; -GO -ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VARCHAR(255) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ProjectID'; -GO -ALTER TABLE onprc_billing.aliases ADD [ProjectID] VARCHAR(100) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ActivityType'; -GO -ALTER TABLE onprc_billing.aliases ADD [ActivityType] VARCHAR(255) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardNumber'; -GO -ALTER TABLE onprc_billing.aliases ADD [AwardNumber] VARCHAR(255) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardSuffix'; -GO -ALTER TABLE onprc_billing.aliases ADD [AwardSuffix] VARCHAR(255) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'Org'; -GO -ALTER TABLE onprc_billing.aliases ADD [Org] VARCHAR(255) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ADFMEmpNum'; -GO -ALTER TABLE onprc_billing.aliases ADD [ADFMEmpNum] VARCHAR(255) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ADFMFullName'; -GO -ALTER TABLE onprc_billing.aliases ADD [ADFMFullName] VARCHAR(255) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ActivityTypeDescription'; -GO -ALTER TABLE onprc_billing.aliases ADD [ActivityTypeDescription] VARCHAR(255) NUll; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'FundingSourceNumber'; -GO -ALTER TABLE onprc_billing.aliases ADD [FUndingSourceNumber] VARCHAR(255) NUll - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'FundingSourceName'; -GO -ALTER TABLE onprc_billing.aliases ADD [FUndingSourceName] VARCHAR(255) NUll - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'Org'; -GO -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 deleted file mode 100644 index feff5121f..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.410-20.411.sql +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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 deleted file mode 100644 index abe314800..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.508-20.509.sql +++ /dev/null @@ -1,55 +0,0 @@ --- 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 -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'; -GO -ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VarChar(255) Null; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationTypeDescription'; -GO -ALTER TABLE onprc_billing.aliases ADD [ApplicationTypeDescription] VarChar(255) Null; - -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardStatus'; -GO -ALTER TABLE onprc_billing.aliases ADD [AwardStatus] VARCHAR(100) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardID'; -GO -ALTER TABLE onprc_billing.aliases ADD [AwardID] VARCHAR(100) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ApplicationType'; -GO -ALTER TABLE onprc_billing.aliases ADD [ApplicationType] VARCHAR(255) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ProjectID'; -GO -ALTER TABLE onprc_billing.aliases ADD [ProjectID] VARCHAR(100) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ActivityType'; -GO -ALTER TABLE onprc_billing.aliases ADD [ActivityType] VARCHAR(255) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardNumber'; -GO -ALTER TABLE onprc_billing.aliases ADD [AwardNumber] VARCHAR(255) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'AwardSuffix'; -GO -ALTER TABLE onprc_billing.aliases ADD [AwardSuffix] VARCHAR(255) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'Org'; -GO -ALTER TABLE onprc_billing.aliases ADD [Org] VARCHAR(255) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ADFMEmpNum'; -GO -ALTER TABLE onprc_billing.aliases ADD [ADFMEmpNum] VARCHAR(255) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ADFMFullName'; -GO -ALTER TABLE onprc_billing.aliases ADD [ADFMFullName] VARCHAR(255) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'ActivityTypeDescription'; -GO -ALTER TABLE onprc_billing.aliases ADD [ActivityTypeDescription] VARCHAR(255) NUll; -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'FundingSourceNumber'; -GO -ALTER TABLE onprc_billing.aliases ADD [FUndingSourceNumber] VARCHAR(255) NUll -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'FundingSourceName'; -GO -ALTER TABLE onprc_billing.aliases ADD [FUndingSourceName] VARCHAR(255) NUll -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'Org'; -GO -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 deleted file mode 100644 index c28c5beb5..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.511-20.512.sql +++ /dev/null @@ -1,22 +0,0 @@ - -/****** 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 ******/ -EXEC core.fn_dropifexists 'OGA_RemoveRecords', 'onprc_billing', 'PROCEDURE' -GO - -CREATE PROCEDURE [onprc_billing].[OGA_RemoveRecords] - AS - BEGIN - - Delete from onprc_billing.aliases - where category != 'OHSU GL' - - - - END - -GO 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 deleted file mode 100644 index 059fa396d..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.512-20.513.sql +++ /dev/null @@ -1,83 +0,0 @@ - -/****** Object: StoredProcedure [onprc_billing].[oga_InsertRecords] Script Date: 5/18/2020 10:35:50 AM ******/ -EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' -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 - -GO 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 deleted file mode 100644 index 9476573c7..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.514-20.515.sql +++ /dev/null @@ -1,100 +0,0 @@ -/****** 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 - -GO 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 deleted file mode 100644 index 53e6ddb70..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.515-20.516.sql +++ /dev/null @@ -1,127 +0,0 @@ - - -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 - -GO diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.910-20.911.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.910-20.911.sql deleted file mode 100644 index c86a7f509..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.910-20.911.sql +++ /dev/null @@ -1,14 +0,0 @@ -/****** Object: StoredProcedure [onprc_billing].[OGA_RemoveRecords] Script Date: 10/15/2020 9:30:00 AM ******/ - -EXEC core.fn_dropifexists 'ClearOGASync', 'onprc_billing', 'PROCEDURE' -GO - -CREATE PROCEDURE [onprc_billing].[ClearOGASync] -AS -BEGIN - -Delete from onprc_billing.ogasynch - -END - -GO diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.911-20.912.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.911-20.912.sql deleted file mode 100644 index 9e782c2dd..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.911-20.912.sql +++ /dev/null @@ -1,86 +0,0 @@ - -/****** Object: StoredProcedure [onprc_billing].[oga_InsertRecords] - Script Date: 5/18/2020 10:35:50 AM -Update 2020-11-25 jonesga to change source of fa rate from burden rate to cast value - ******/ -EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' -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' - ,[farate] - ,[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 - -GO diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.912-20.913.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.912-20.913.sql deleted file mode 100644 index 6ab8e697d..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.912-20.913.sql +++ /dev/null @@ -1,90 +0,0 @@ - -/****** Object: StoredProcedure [onprc_billing].[oga_InsertRecords] - Script Date: 5/18/2020 10:35:50 AM -Update 2020-11-25 jonesga to change source of fa rate from burden rate to cast value - ******/ -EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' -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], - Case - when [ALIAS ENABLED FLAG] = 1 then 'y' - when [ALIAS ENABLED FLAG] = 0 then 'n' - End as AliasEnabled - -- ,[ALIAS ENABLED FLAG] - ,[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' - ,[farate] - ,[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 -GO diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.913-20.914.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.913-20.914.sql deleted file mode 100644 index 3be7b58ea..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.913-20.914.sql +++ /dev/null @@ -1,91 +0,0 @@ -/****** Object: StoredProcedure [onprc_billing].[oga_InsertRecords] Script Date: 12/2/2020 12:18:09 PM ******/ -EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' -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], - Case - when [ALIAS ENABLED FLAG] = 1 then 'y' - when [ALIAS ENABLED FLAG] = 0 then 'n' - End as AliasEnabled - - ,[OGA PROJECT NUMBER] - ,[OGA AWARD NUMBER] - ,[AGENCY AWARD NUMBER] - ,i.rowId - --End as [PI EMP NUM] - ,[PI FULL NAME] - ,f.rowid - --,[PDFM EMP NUM] - ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' - ,1003 - ,GetDate() - ,'OGA' - ,[farate] - ,[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] o - left outer join [onprc_ehr].investigators i on o.[PI EMP NUM] = i.employeeid - left outer join onprc_billing.fiscalAuthorities f on f.employeeId = o.[PDFM EMP NUM] -END -GO diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.914-20.915.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.914-20.915.sql deleted file mode 100644 index 0a0bd5302..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.914-20.915.sql +++ /dev/null @@ -1,87 +0,0 @@ -EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' -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], - Case - when [ALIAS ENABLED FLAG] = 1 then 'y' - when [ALIAS ENABLED FLAG] = 0 then 'n' - End as AliasEnabled - - ,[OGA PROJECT NUMBER] - ,[OGA AWARD NUMBER] - ,[AGENCY AWARD NUMBER] - ,i.rowId - --End as [PI EMP NUM] - ,[PI FULL NAME] - ,f.rowid - --,[PDFM EMP NUM] - ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' - ,1003 - ,GetDate() - ,'OGA' - ,[farate] - ,[BURDEN SCHEDULE] - ,[CURRENT BUDGET START DATE] - ,[CURRENT BUDGET END DATE] - ,[PROJECT TITLE] - ,[PROJECT DESCRIPTION] - ,[PROJECT STATUS] - ,[OGA AWARD 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] o - left outer join [onprc_ehr].investigators i on o.[PI EMP NUM] = i.employeeid - left outer join onprc_billing.fiscalAuthorities f on f.employeeId = o.[PDFM EMP NUM] -END -GO diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.916-20.917.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.916-20.917.sql deleted file mode 100644 index 97624e13c..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.916-20.917.sql +++ /dev/null @@ -1,88 +0,0 @@ -EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' -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], - Case - when [ALIAS ENABLED FLAG] = 1 then 'y' - when [ALIAS ENABLED FLAG] = 0 then 'n' - End as AliasEnabled - - ,[OGA PROJECT NUMBER] - ,[OGA AWARD NUMBER] - ,[AGENCY AWARD NUMBER] - ,i.rowId - --End as [PI EMP NUM] - ,[PI FULL NAME] - ,f.rowid - --,[PDFM EMP NUM] - ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' - ,1003 - ,GetDate() - ,'OGA' - ,[farate] - ,[BURDEN SCHEDULE] - ,[CURRENT BUDGET START DATE] - ,[CURRENT BUDGET END DATE] - ,[PROJECT TITLE] - ,[PROJECT DESCRIPTION] - ,[PROJECT STATUS] - ,[OGA AWARD 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] o - left outer join [onprc_ehr].investigators i on o.[PI EMP NUM] = i.employeeid and i.datedisabled is Null - left outer join onprc_billing.fiscalAuthorities f on f.employeeId = o.[PDFM EMP NUM] and f.active = 'true'; - -END -GO diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.917-20.918.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.917-20.918.sql deleted file mode 100644 index 97624e13c..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-20.917-20.918.sql +++ /dev/null @@ -1,88 +0,0 @@ -EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' -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], - Case - when [ALIAS ENABLED FLAG] = 1 then 'y' - when [ALIAS ENABLED FLAG] = 0 then 'n' - End as AliasEnabled - - ,[OGA PROJECT NUMBER] - ,[OGA AWARD NUMBER] - ,[AGENCY AWARD NUMBER] - ,i.rowId - --End as [PI EMP NUM] - ,[PI FULL NAME] - ,f.rowid - --,[PDFM EMP NUM] - ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' - ,1003 - ,GetDate() - ,'OGA' - ,[farate] - ,[BURDEN SCHEDULE] - ,[CURRENT BUDGET START DATE] - ,[CURRENT BUDGET END DATE] - ,[PROJECT TITLE] - ,[PROJECT DESCRIPTION] - ,[PROJECT STATUS] - ,[OGA AWARD 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] o - left outer join [onprc_ehr].investigators i on o.[PI EMP NUM] = i.employeeid and i.datedisabled is Null - left outer join onprc_billing.fiscalAuthorities f on f.employeeId = o.[PDFM EMP NUM] and f.active = 'true'; - -END -GO diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-22.001-22.002.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-22.001-22.002.sql deleted file mode 100644 index 473f6eef6..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-22.001-22.002.sql +++ /dev/null @@ -1,5 +0,0 @@ -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'Originating Agency Award Number'; -GO -ALTER TABLE onprc_billing.aliases ADD [OriginatingAgencyAwardNum] VarChar(255) Null; -GO -ALTER TABLE onprc_billing.ogaSynch ADD [ORIGINATING_AGENCY_AWARD_NUM] VarChar(255) Null; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-22.003-22.004.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-22.003-22.004.sql deleted file mode 100644 index cf7507ff0..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-22.003-22.004.sql +++ /dev/null @@ -1,90 +0,0 @@ ---20220406 update of SP for insert -EXEC core.fn_dropifexists 'oga_InsertRecords', 'onprc_billing', 'PROCEDURE' -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] -,[OriginatingAgencyAwardNum] -) -SELECT - [Alias], - Case - when [ALIAS ENABLED FLAG] = 1 then 'y' - when [ALIAS ENABLED FLAG] = 0 then 'n' - End as AliasEnabled - - ,[OGA PROJECT NUMBER] - ,[OGA AWARD NUMBER] - ,[AGENCY AWARD NUMBER] - ,i.rowId - --End as [PI EMP NUM] - ,[PI FULL NAME] - ,f.rowid - --,[PDFM EMP NUM] - ,'0F8BB08E-E4BF-102F-B89B-5107380A5B61' - ,1003 - ,GetDate() - ,'OGA' - ,[farate] - ,[BURDEN SCHEDULE] - ,[CURRENT BUDGET START DATE] - ,[CURRENT BUDGET END DATE] - ,[PROJECT TITLE] - ,[PROJECT DESCRIPTION] - ,[PROJECT STATUS] - ,[OGA AWARD 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] - ,[ORIGINATING_AGENCY_AWARD_NUM] - From [onprc_billing].[ogasynch] o - left outer join [onprc_ehr].investigators i on o.[PI EMP NUM] = i.employeeid and i.datedisabled is Null - left outer join onprc_billing.fiscalAuthorities f on f.employeeId = o.[PDFM EMP NUM] and f.active = 'true'; - -END -GO diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-22.004-22.005.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-22.004-22.005.sql deleted file mode 100644 index 333ef2508..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-22.004-22.005.sql +++ /dev/null @@ -1,7 +0,0 @@ -EXEC core.fn_dropifexists 'aliases', 'onprc_billing', 'COLUMN', 'OriginatingAgencyAwardNum'; -GO -EXEC core.fn_dropifexists 'ogaSynch', 'onprc_billing', 'COLUMN', 'ORIGINATING_AGENCY_AWARD_NUM'; -GO -ALTER TABLE onprc_billing.aliases ADD [OriginatingAgencyAwardNum] VarChar(255) Null; -GO -ALTER TABLE onprc_billing.ogaSynch ADD [ORIGINATING_AGENCY_AWARD_NUM] VarChar(255) Null; \ No newline at end of file diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-23.002-23.003.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-23.002-23.003.sql deleted file mode 100644 index 30d8754c2..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-23.002-23.003.sql +++ /dev/null @@ -1,19 +0,0 @@ -IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'UpdateClinPathEndDate') -DROP PROCEDURE UpdateClinPathEndDate - GO -CREATE PROCEDURE onprc_billing.UpdateClinPathEndDate - - AS -BEGIN - --Updates end Date for ClinPath when complete but no dateUpdate [Labkey_uat].[studyDataset].[c6d199_clinpathruns] - --update todya 8/16/2023 -Update [studyDataset].[c6d199_clinpathruns] -set datefinalized = date -where dateFinalized is null and date > '5/1/2023' and qcstate = 18 - - - - - -END -GO diff --git a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-23.003-23.004.sql b/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-23.003-23.004.sql deleted file mode 100644 index 40b8b5a35..000000000 --- a/onprc_billing/resources/schemas/dbscripts/sqlserver/onprc_billing-23.003-23.004.sql +++ /dev/null @@ -1,2 +0,0 @@ -/*Corrected to remove sql script not related to this module.*/ -EXEC core.fn_dropifexists 'annualinflationrate','onprc_billing','table',Null 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 af2f65ae5..0d132cfed 100644 --- a/onprc_billing/src/org/labkey/onprc_billing/ONPRC_BillingModule.java +++ b/onprc_billing/src/org/labkey/onprc_billing/ONPRC_BillingModule.java @@ -83,13 +83,7 @@ public String getName() @Override public @Nullable Double getSchemaVersion() { - return 25.006; - } - - @Override - public boolean hasScripts() - { - return true; + return 26.000; } @Override diff --git a/onprc_billingpublic/module.properties b/onprc_billingpublic/module.properties index 800332029..8e2ae812d 100644 --- a/onprc_billingpublic/module.properties +++ b/onprc_billingpublic/module.properties @@ -1,5 +1,5 @@ ModuleClass: org.labkey.onprc_billingpublic.ONPRC_BillingPublicModule -SupportedDatabases: mssql +SupportedDatabases: mssql, pgsql License: Apache 2.0 LicenseURL: http://www.apache.org/licenses/LICENSE-2.0 ManageVersion: false diff --git a/onprc_ehr/module.properties b/onprc_ehr/module.properties index 02cfcfa45..df3ab0804 100644 --- a/onprc_ehr/module.properties +++ b/onprc_ehr/module.properties @@ -1,3 +1,3 @@ ModuleClass: org.labkey.onprc_ehr.ONPRC_EHRModule -SupportedDatabases: mssql -ManageVersion: false +SupportedDatabases: mssql, pgsql +ManageVersion: true diff --git a/onprc_ehr/resources/etls/ClinicalObservation_TestScores.xml b/onprc_ehr/resources/etls/ClinicalObservation_TestScores.xml new file mode 100644 index 000000000..528ef8f98 --- /dev/null +++ b/onprc_ehr/resources/etls/ClinicalObservation_TestScores.xml @@ -0,0 +1,53 @@ + + + + + Clinical_Observation_TestScores_Process + + Create new sets of Clinical Observation Test Scores + + + + + + Runs a stored procedure that generates Clinical Observation Test Scores + + + + + + + + Transfer ehr_task temp to EHR Tasks + + + + + + + + + + Transfer temp data to Study Clinical Observations + + + + + + + + + + + + + + + + + + + + + + diff --git a/onprc_ehr/resources/queries/onprc_ehr/MedsEndDateAlert.sql b/onprc_ehr/resources/queries/onprc_ehr/MedsEndDateAlert.sql index a6dc2db26..83d52ee3d 100644 --- a/onprc_ehr/resources/queries/onprc_ehr/MedsEndDateAlert.sql +++ b/onprc_ehr/resources/queries/onprc_ehr/MedsEndDateAlert.sql @@ -9,14 +9,17 @@ Added Diet to the list by Kollil on 5/14/25. Refer to tkt #12506 5. E-X1380 - Diet Daily (Non-standard), 5LOP (TAD) + + Added Diet to the list by Kollil on 8/5/2026. Refer to tkt #15123 +6. E-YYY85 - Diet, 5000 Chow */ SELECT Id, - date, + CAST(date AS DATE) AS date, enddate, - frequency, + frequency.meaning as frequency, treatmenttimes, - project, + project.displayname as project, code, volumewithunits, concentrationwithunits, @@ -25,10 +28,11 @@ SELECT performedby, remark, reason, - modifiedby, - modified, + modifiedby.displayname as modifiedby, + CAST(modified AS DATE) AS modified, category, + qcstate.label as qcstate, taskid.rowid as TaskId FROM study.treatment_order -WHERE code NOT IN ('E-85760', 'E-Y7735', 'E-X0500', 'E-Y9750', 'E-X1380') +WHERE code NOT IN ('E-85760', 'E-Y7735', 'E-X0500', 'E-Y9750', 'E-X1380', 'E-YYY85') AND enddate is null \ No newline at end of file diff --git a/onprc_ehr/resources/queries/study/AlopeciaScoreMissingBehaviorCases.query.xml b/onprc_ehr/resources/queries/study/AlopeciaScoreMissingBehaviorCases.query.xml new file mode 100644 index 000000000..a7f5d6805 --- /dev/null +++ b/onprc_ehr/resources/queries/study/AlopeciaScoreMissingBehaviorCases.query.xml @@ -0,0 +1,10 @@ + + + + + + Animals with alopecia score 4 or 5 with missing behavior cases +
+
+
+
diff --git a/onprc_ehr/resources/queries/study/AlopeciaScoreMissingBehaviorCases.sql b/onprc_ehr/resources/queries/study/AlopeciaScoreMissingBehaviorCases.sql index 0096f2725..dc670937a 100644 --- a/onprc_ehr/resources/queries/study/AlopeciaScoreMissingBehaviorCases.sql +++ b/onprc_ehr/resources/queries/study/AlopeciaScoreMissingBehaviorCases.sql @@ -5,11 +5,18 @@ Show 1 year data. Modified by Kollil 09/15/2025 Added date comparison to check only dates and ignore time + +Modified by Kollil July 2026 +Showing only 1 month data, Refer to tkt # 14974 */ SELECT mr.Id, d.species, - d.gender, + CASE + WHEN LOWER(d.gender) = 'f' THEN 'Female' + WHEN LOWER(d.gender) = 'm' THEN 'Male' + ELSE d.gender + END AS gender, d.Id.age.ageinYearsRounded, d.Id.curLocation.area, d.Id.curLocation.room, @@ -22,14 +29,14 @@ FROM ( FROM study.clinical_observations AS co WHERE co.category = 'Alopecia Score' - AND co.created >= TIMESTAMPADD(SQL_TSI_YEAR, -1, NOW()) + AND co.created >= TIMESTAMPADD(SQL_TSI_MONTH, -1, NOW()) AND co.created = ( SELECT MAX(co2.created) FROM study.clinical_observations AS co2 WHERE co2.Id = co.Id AND co2.category = 'Alopecia Score' - AND co2.created >= TIMESTAMPADD(SQL_TSI_YEAR, -1, NOW()) + AND co2.created >= TIMESTAMPADD(SQL_TSI_MONTH, -1, NOW()) ) ) AS mr INNER JOIN study.demographics AS d ON mr.Id = d.Id @@ -43,8 +50,6 @@ WHERE c.Id = mr.Id AND c.category = 'Behavior' AND c.allProblemCategories = 'Behavioral: Alopecia' --- AND c.date <= mr.date --- AND (c.enddate IS NULL OR c.enddate > mr.date) AND CAST(c.date AS DATE) <= CAST(mr.date AS DATE) AND (c.enddate IS NULL OR CAST(c.enddate AS DATE) >= CAST(mr.date AS DATE)) ) diff --git a/onprc_ehr/resources/queries/study/AssignmentPoolUnderTheAge.query.xml b/onprc_ehr/resources/queries/study/AssignmentPoolUnderTheAge.query.xml index 2d839c69e..584c6110f 100644 --- a/onprc_ehr/resources/queries/study/AssignmentPoolUnderTheAge.query.xml +++ b/onprc_ehr/resources/queries/study/AssignmentPoolUnderTheAge.query.xml @@ -3,7 +3,7 @@ - Animals under the age of 3 with an assignment pool note + Animals under the age of 3 with an assignment pool flag
diff --git a/onprc_ehr/resources/queries/study/AssignmentPoolUnderTheAge.sql b/onprc_ehr/resources/queries/study/AssignmentPoolUnderTheAge.sql index da5ff511a..a22cad638 100644 --- a/onprc_ehr/resources/queries/study/AssignmentPoolUnderTheAge.sql +++ b/onprc_ehr/resources/queries/study/AssignmentPoolUnderTheAge.sql @@ -1,22 +1,18 @@ -/* Added by Kollil, Jan 2026 - Refer to tkt # 14056 - - Extract animals under the age of 2.5 with an "Assignment pool" note in PRIMe (under general>notes) - */ +-- /* Added by Kollil, June 2026 +-- Refer to tkt # 14056 +-- Instead of a general > note, they now have a flag - Category: Assign Alias, Meaning: Assignment pool. +-- I think we could keep the grid the same, except replace the field "notes pertaining to DAR" with +-- the "Meaning" field from the active flags page. Although could we rename the column so it's called "Flag"? +-- */ SELECT a.Id, a.Id.demographics.gender AS Sex, - a.Id.Age.ageinyears, + a.Id.Age.ageinyears AS Age, a.Id.curlocation.room AS Room, a.Id.curlocation.cage AS Cage, - /* Display the (active) Notes Pertaining to DAR note text */ - ( - SELECT MAX(n.value) - FROM study.Notes n - WHERE n.Id = a.Id - AND n.category = 'Notes Pertaining to DAR' - AND n.endDate IS NULL - ) AS Notes_Pertaining_to_DAR, + 'Assignment Pool' AS Flag, + /* Concatenate all active cagemate IDs into one cell */ ( SELECT GROUP_CONCAT(DISTINCT CAST(h.roommateId AS VARCHAR), ', ') @@ -26,31 +22,35 @@ SELECT AND h.roommateEnd IS NULL AND h.roommateId IS NOT NULL ) AS Cagemates, + /* Concatenate all active projects & investigator into one cell */ ( SELECT GROUP_CONCAT(DISTINCT CAST('[' + d.project.protocol.investigatorId.lastname + ']' + d.project.displayname + '' AS VARCHAR), ', ') FROM housingRoommatesDivider h LEFT JOIN study.assignment d ON d.Id = h.roommateId WHERE h.Id = a.Id - AND h.removalDate IS NULL - AND h.roommateEnd IS NULL - AND h.roommateId IS NOT NULL - AND d.enddate IS NULL - AND d.isActive = 1 - AND d.project.displayname NOT IN ('0492-02', '0492-03') + AND h.removalDate IS NULL + AND h.roommateEnd IS NULL + AND h.roommateId IS NOT NULL + AND d.enddate IS NULL + AND d.isActive = 1 + AND d.project.displayname NOT IN ('0492-02', '0492-03') ) AS Cagemate_Assignments -FROM Assignment a +FROM study.Assignment a WHERE a.Id.Age.ageinyears <= 3 - AND a.project.displayname NOT IN ('0492-02', '0492-03') + --Remove these filters + --a.enddate IS NULL + --AND a.isActive = 1 + --AND a.project.displayname NOT IN ('0492-02', '0492-03') AND a.Id.demographics.species = 'Rhesus Macaque' AND EXISTS ( SELECT 1 - FROM study.Notes n - WHERE n.Id = a.Id - AND n.value LIKE '%Assignment pool%' - AND n.endDate IS NULL - ) - + FROM study.flags f + WHERE f.Id = a.Id + AND f.flag.category = 'Assign Alias' + AND f.flag.value = 'Assignment Pool' + AND f.enddate IS NULL +) diff --git a/onprc_ehr/resources/queries/study/clinremarks/.qview.xml b/onprc_ehr/resources/queries/study/clinremarks/.qview.xml index 9f5ac339e..1196a662a 100644 --- a/onprc_ehr/resources/queries/study/clinremarks/.qview.xml +++ b/onprc_ehr/resources/queries/study/clinremarks/.qview.xml @@ -10,6 +10,8 @@ + + diff --git a/onprc_ehr/resources/queries/study/demographicsCurrentRoommates.query.xml b/onprc_ehr/resources/queries/study/demographicsCurrentRoommates.query.xml new file mode 100644 index 000000000..0f8c4449b --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographicsCurrentRoommates.query.xml @@ -0,0 +1,37 @@ + + + + + + + true + true + + + # Cagemates + The total number of animals in this cage, excluding the current animal + /query/executeQuery.view?schemaName=study& + query.queryName=housing& + query.room~eq=${Id/curLocation/room/room}& + query.cage~eq=${Id/curLocation/cage}& + query.enddate~isblank& + query.sort=Id& + + + + Total Animals In Cage + The total number of animals in this cage, including the current animal + /query/executeQuery.view?schemaName=study& + query.queryName=housing& + query.room~eq=${Id/curLocation/room/room}& + query.cage~eq=${Id/curLocation/cage}& + query.enddate~isblank& + query.sort=Id& + + + + NumRoommates +
+
+
+
diff --git a/onprc_ehr/resources/queries/study/demographicsCurrentRoommates.sql b/onprc_ehr/resources/queries/study/demographicsCurrentRoommates.sql new file mode 100644 index 000000000..ccfc35576 --- /dev/null +++ b/onprc_ehr/resources/queries/study/demographicsCurrentRoommates.sql @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2010-2019 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +SELECT + d.id, + count(DISTINCT h.RoommateId) as NumRoommates, + (count(DISTINCT h.RoommateId)+1) as AnimalsInCage, + group_concat(DISTINCT h.RoommateId,', ') as cagemates + +FROM study.demographics d +LEFT JOIN ( + SELECT + h1.id, + h2.id as RoommateId + FROM study.Housing h1 + LEFT OUTER JOIN study.Housing h2 ON ( + h1.enddate IS NULL AND -- only look at current housing assignments (no end date) + h2.enddate IS NULL AND -- only look at current housing assignments (no end date) + h1.id != h2.id AND -- don't include self as roommate + h1.room = h2.room AND -- Make sure room matches + (h1.cage = h2.cage OR (h1.cage is null and h2.cage is null)) -- make sure cage matches + ) + WHERE h1.qcstate.publicdata = true AND h2.qcstate.publicdata = true +) h + ON (h.id = d.id) + +WHERE d.calculated_status='Alive' + +GROUP BY d.id diff --git a/onprc_ehr/resources/queries/study/pregnancyGestation.sql b/onprc_ehr/resources/queries/study/pregnancyGestation.sql index 5fbcd63eb..685b967ca 100644 --- a/onprc_ehr/resources/queries/study/pregnancyGestation.sql +++ b/onprc_ehr/resources/queries/study/pregnancyGestation.sql @@ -18,16 +18,17 @@ SELECT m.id, m.date, m.gestation_days as gestation_days, -TIMESTAMPADD('SQL_TSI_DAY',(p.Gestation - m.gestation_days), m.date) as ExpectedDelivery, -m.QCState + TIMESTAMPADD('SQL_TSI_DAY',(p.Gestation - m.gestation_days), m.date) as ExpectedDelivery, + m.QCState FROM study.pregnancyConfirmation m INNER JOIN ehr_lookups.species p on (m.Id.DataSet.demographics.species = p.common ) And m.date in (select max(s.date) AS d from study.pregnancyConfirmation s where s.id = m.id) And m.Id.DataSet.demographics.calculated_status.code = 'Alive' -And p.Gestation is not null And (m.outcome.birthDate >= cast(now() as date) or m.outcome.birthDate is null) And (Select count(*) from ehr.snomed_tags stg where stg.code.code = 'F-30980' And stg.id = m.id And stg.date >= m.date ) = 0 And m.gestation_days is not null +And p.Gestation is not null + diff --git a/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-0.000-25.000.sql b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-0.000-25.000.sql new file mode 100644 index 000000000..4a8acfdf1 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-0.000-25.000.sql @@ -0,0 +1,1677 @@ +/* + * 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_ehr; + +CREATE TABLE onprc_ehr.etl_runs +( + RowId SERIAL, + date TIMESTAMP, + Container ENTITYID NOT NULL, + queryname varchar(200), + rowversion varchar(200), + + CONSTRAINT PK_etl_runs PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_ehr.investigators ( + rowId SERIAL 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 TIMESTAMP, + dateDisabled TIMESTAMP, + division varchar(100), + financialAnalyst int, + createdby userid, + created TIMESTAMP, + modifiedby userid, + modified TIMESTAMP, + objectid ENTITYID, + assignedVet int, + userid int, + employeeid varchar(100), + Department varchar(250) NULL, + + CONSTRAINT pk_investigators PRIMARY KEY (rowid) +); + +CREATE INDEX investigators_rowid_lastname ON onprc_ehr.investigators (rowid, lastname); + +CREATE TABLE onprc_ehr.serology_test_schedule ( + rowid SERIAL, + code varchar(100), + flag varchar(100), + interval int, + species VARCHAR(100), + + 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); + +CREATE TABLE onprc_ehr.customers ( + rowId SERIAL 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 TIMESTAMP, + dateDisabled TIMESTAMP, + investigatorId int, + objectid entityid, + container entityid, + createdby userid, + created TIMESTAMP, + modifiedby userid, + modified TIMESTAMP, + + CONSTRAINT pk_customers PRIMARY KEY (rowid) +); + +-- TODO: Should delete, no longer needed for PostgreSQL +-- 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 SERIAL, + userid int, + area varchar(100), + protocol varchar(100), + container ENTITYID NOT NULL, + created TIMESTAMP, + createdby int, + modified TIMESTAMP, + modifiedby int, + room varchar(100), + priority BOOLEAN, + project INT, + + CONSTRAINT PK_vet_assignment PRIMARY KEY (rowid) +); + +CREATE TABLE onprc_ehr.housing_transfer_requests ( + Id varchar(100), + date TIMESTAMP, + room varchar(200), + cage varchar(100), + reason varchar(100), + remark varchar(4000), + qcstate int, + requestid entityid, + objectid entityid NOT NULL, + container entityid, + created TIMESTAMP, + createdby int, + modified TIMESTAMP, + modifiedby int, + divider integer, + formSort integer, + + CONSTRAINT PK_housing_transfer_requests PRIMARY KEY (objectid) +); + +UPDATE ehr.tasks SET formtype = 'Bulk Clinical Entry' WHERE lower(formtype) = lower('Clinical Remarks'); + +CREATE TABLE onprc_ehr.birth_condition ( + rowid SERIAL, + value varchar(200), + alive BOOLEAN, + description varchar(4000), + container entityid, + createdby int, + created TIMESTAMP, + modifiedby int, + modified TIMESTAMP, + + CONSTRAINT PK_birth_condition PRIMARY KEY (rowid) +); + +UPDATE ehr.qcStateMetadata SET draftData = TRUE WHERE lower(QCStateLabel) = lower('Request: Pending'); + +CREATE TABLE onprc_ehr.encounter_summaries_remarks ( + id varchar(100), + date TIMESTAMP, + parentid entityid, + schemaName varchar(100), + queryName varchar(100), + remark text, + objectid varchar(60) NOT NULL, + container entityid NOT NULL, + createdby userid, + created TIMESTAMP, + modifiedby userid, + modified TIMESTAMP, + taskid entityid, + category varchar(100), + formsort integer, + + CONSTRAINT pk_encounter_summaries_remarks PRIMARY KEY (objectid) +); + +CREATE TABLE onprc_ehr.NHP_Training( + RowId SERIAL NOT NULL, + Id varchar(100), + date TIMESTAMP NULL, + training_Ending_Date TIMESTAMP NULL, + training_type varchar(255) NULL, + reason varchar(255) NULL, + qcstate INTEGER NULL, + taskid varchar(4000) NULL, + remark varchar(4000) NULL, + objectid ENTITYID NOT NULL, + formSort SMALLINT NULL, + performedby varchar(4000) NULL, + createdby int NULL, + created TIMESTAMP NULL, + modifiedby int NULL, + modified TIMESTAMP NULL, + Container ENTITYID, + training_results varchar(255) NULL, + + CONSTRAINT PK_NHPTrainingObject PRIMARY KEY (objectid) +); + +CREATE TABLE onprc_ehr.AvailableBloodVolume( + datecreated TIMESTAMP NULL, + id varchar(32) NOT NULL, + gender varchar(4000) NULL, + species varchar(4000) NULL, + yoa double precision NULL, + mostrecentweightdate TIMESTAMP NULL, + weight double precision NULL, + calcmethod varchar(32) NULL, + BCS double precision NULL, + BCSage int NULL, + previousdraws double precision NULL, + ABV double precision NULL, + dsrowid bigint NOT NULL, + + CONSTRAINT PK_AvailableBloodVolume PRIMARY KEY (Id) +); + +CREATE TABLE onprc_ehr.Reference_StaffNames( + RowId SERIAL 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 TIMESTAMP NULL, + DisableDate TIMESTAMP NULL, + + CONSTRAINT pk_reference PRIMARY KEY (username) +); + +CREATE TABLE onprc_ehr.Frequency_DayofWeek( + RowId SERIAL NOT NULL, + FreqKey SMALLINT NULL, + value SMALLINT NULL, + Meaning varchar(400) NULL, + calenderType varchar(100) NULL, + Sort_order SMALLINT NULL, + DisableDate TIMESTAMP NULL, + + CONSTRAINT pk_FreqWeek PRIMARY KEY (RowId) +); + +CREATE TABLE onprc_ehr.usersActiveNames( + Email varchar(64) NULL, + _ts TIMESTAMP DEFAULT now(), + EntityId ENTITYID NULL, + CreatedBy USERID NULL, + Created TIMESTAMP NULL, + ModifiedBy USERID NULL, + Modified TIMESTAMP NULL, + Owner USERID NULL, + UserId USERID NOT NULL, + DisplayName varchar(64) NOT NULL, + FirstName varchar(64) NULL, + LastName varchar(64) NULL, + Phone varchar(64) NULL, + Mobile varchar(64) NULL, + Pager varchar(64) NULL, + IM varchar(64) NULL, + Description varchar(255) NULL, + LastLogin TIMESTAMP NULL, + Active BOOLEAN NOT NULL +); + +CREATE TABLE onprc_ehr.eIACUC_PRIME_VIEW_ANIMAL_GROUPS( + rowid SERIAL 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 text NULL, + Non_Standard_Housing_Description text NULL, + Non_Standard_Housing_Frequency_and_Duration text NULL, + Non_Standard_Housing_Monitoring text NULL, + createdby int NULL, + created TIMESTAMP NULL, + modifiedby int NULL, + modified TIMESTAMP NULL, + Restraint text NULL, + Nutritional_Manipulation_Description text NULL, + Nutritional_Manipulation_Adverse_Consequences text NULL, + Nutritional_Manipulation_Health_Assessment text NULL, + Non_Pharmaceutical_Grade_Drug_Use text NULL, + Food_Withheld int NULL, + Water_Withheld int NULL, + Food_Water_Withheld_Description text NULL, + Food_Water_Withheld_Justification text NULL, + Food_Water_Withheld_Adverse_Consequences text NULL, + Death_As_Endpoint_Number_of_Animals text NULL, + Death_As_Endpoint_Justification text NULL +); + +CREATE TABLE onprc_ehr.eIACUC_PRIME_VIEW_IBC_NUMBERS( + rowid SERIAL NOT NULL, + Animal_Group varchar(255) NOT NULL, + IBC_Registration_Number varchar(255) NULL, + createdby int NULL, + created TIMESTAMP NULL, + modifiedby int NULL, + modified TIMESTAMP NULL +); + +CREATE TABLE onprc_ehr.eIACUC_PRIME_VIEW_NON_SURGICAL_PROCS( + rowid SERIAL 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 TIMESTAMP NULL, + modifiedby int NULL, + modified TIMESTAMP NULL +); + +CREATE TABLE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS( + rowid SERIAL 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 TIMESTAMP NULL, + Annual_Update_Due TIMESTAMP NULL, + Three_year_Expiration TIMESTAMP NULL, + Last_Modified TIMESTAMP NULL, + createdby int NULL, + created TIMESTAMP NULL, + modifiedby int NULL, + modified TIMESTAMP NULL, + PROTOCOL_State varchar(250) NULL, + PPQ_Numbers varchar(255) NULL, + Description varchar(255) NULL, + BaseProtocol varchar(100) NULL, + RevisionNumber varchar(100) NULL, + NewestRecord INT NULL +); + +CREATE TABLE onprc_ehr.eIACUC_PRIME_VIEW_SURGICAL_PROCS( + rowid SERIAL 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 +); + +CREATE TABLE onprc_ehr.PotentialSire_source( + RowId SERIAL NOT NULL, + participantId varchar(32) NULL, + Date TIMESTAMP NULL, + Species varchar(100) NULL, + room varchar(100) NULL, + cage varchar(100) NULL, + SireAgeAtTime integer NULL, -- TODO: Check this - DateTime type on SQL Server, but looks like INTEGER is the correct type + PotentialSire varchar(100) NULL, + SireBirth TIMESTAMP NULL, + Siregender varchar(100) NULL, + Sirespecies varchar(100) NULL, + SireDeath TIMESTAMP NULL, + created TIMESTAMP NULL, + createdBy int NULL, + modified TIMESTAMP NULL, + modifiedBy int NULL, + container ENTITYID, + + CONSTRAINT pk_potentialSire PRIMARY KEY (rowID) +); + +CREATE TABLE onprc_ehr.PotentialDam_source( + RowId SERIAL NOT NULL, + participantId varchar(32) NULL, + Date TIMESTAMP NULL, + Species varchar(100) NULL, + room varchar(100) NULL, + cage varchar(100) NULL, + DamAgeAtTime integer NULL, -- TODO: Check this - DateTime type on SQL Server, but looks like INTEGER is the correct type + PotentialDam varchar(100) NULL, + DamBirth TIMESTAMP NULL, + Damgender varchar(100) NULL, + DamSpecies varchar(100) NULL, + DamDeath TIMESTAMP NULL, + created TIMESTAMP NULL, + createdBy int NULL, + modified TIMESTAMP NULL, + modifiedBy int NULL, + container ENTITYID, + + CONSTRAINT pk_potentialDam PRIMARY KEY (rowID) +); + +CREATE TABLE onprc_ehr.PotentialParents_source( + RowId SERIAL NOT NULL, + participantId varchar(32) NULL, + BirthDate TIMESTAMP NULL, + Species varchar(100) NULL, + BirthRoom varchar(100) NULL, + Birthcage varchar(100) NULL, + ParentAgeAtTime integer NULL, -- TODO: Check this - DateTime type on SQL Server, but looks like INTEGER is the correct type + PotentialParent varchar(100) NULL, + "[PotentialParentType" varchar(100) NULL, -- TODO: Keep this random bracket for now (to match SQL Server script). Should rename in a separate upgrade script, perhaps after migration work. + ParentBirth TIMESTAMP NULL, + Parentgender varchar(100) NULL, + ParentSpecies varchar(100) NULL, + ParentDeath TIMESTAMP NULL, + created TIMESTAMP NULL, + createdBy int NULL, + modified TIMESTAMP NULL, + modifiedBy int NULL, + container ENTITYID, + + CONSTRAINT pk_potentialParent PRIMARY KEY (rowID) +); + +CREATE OR REPLACE FUNCTION onprc_ehr.PotentialSire_Insert() RETURNS void AS $$ +BEGIN + TRUNCATE TABLE onprc_ehr.PotentialSire_source RESTART IDENTITY; + 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, + (b.date::date - d.birth::date) / 365, + h.participantID, + d.birth, + d.gender, + d.species, + d.death, + now(), + 1011, + now(), + 1011, + 'CD17027B-C55F-102F-9907-5107380A54BE'::entityid + 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)) + 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 lower(d.gender) = lower('m') AND (b.date::date - d.birth::date) > 912.5 + AND d.species = d1.species; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION onprc_ehr.PotentialDam_Insert() RETURNS void AS $$ +BEGIN + TRUNCATE TABLE onprc_ehr.PotentialDam_source RESTART IDENTITY; + 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, + (b.date::date - d.birth::date) / 365, + h.participantID, + d.birth, + d.gender, + d.species, + d.death, + now(), + 1011, + now(), + 1011, + 'CD17027B-C55F-102F-9907-5107380A54BE'::entityid + 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)) + 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 lower(d.gender) = lower('f') AND (b.date::date - d.birth::date) > 912.5 + AND d.species = d1.species; +END; +$$ LANGUAGE plpgsql; + +CREATE TABLE onprc_ehr.StudyDetails_Reference_Data( + rowId SERIAL NOT NULL, + value varchar(1000) NULL, + name varchar(1000) NULL, + remark varchar(4000) NULL, + sort_order INT NULL, + dateDisabled TIMESTAMP NULL, + created TIMESTAMP NULL, + createdBy int NULL, + modified TIMESTAMP NULL, + modifiedBy int NULL, + + CONSTRAINT pk_StudyDetails_Reference_Data PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_ehr.availableCages_temp( + location varchar(50) NOT NULL, + room varchar(200) NULL, + cage varchar(200) NULL, + row varchar(200) NULL, + columnidx int NULL, + cage_type varchar(200) NULL, + lowerCage varchar(200) NULL, + lower_cage_type varchar(200) NULL, + divider int NULL, + isAvailable int NULL, + isMarkedUnavailable int NULL +); + +CREATE TABLE onprc_ehr.availableCagesByRoom_temp( + room varchar(200) NULL, + availableCages int NULL, + markedUnavailable int NULL +); + +CREATE TABLE onprc_ehr.roomUtilization_temp( + room varchar(200) NULL, + availableCages int NULL, + cagesUsed int NULL, + markedUnavailable int NULL, + cagesEmpty int NULL, + totalAnimals int NULL +); + +CREATE OR REPLACE FUNCTION onprc_ehr.NHPRoomsUsage() RETURNS void AS $$ +BEGIN + DELETE FROM onprc_ehr.availableCages_temp; + + INSERT INTO onprc_ehr.availableCages_temp(location, room, cage, row, columnidx, cage_type, lowerCage, lower_cage_type, divider, isAvailable, isMarkedUnavailable) + SELECT + CASE + WHEN c.cage IS NULL THEN c.room + ELSE (c.room || '-' || c.cage) + END as location, + c.room, + c.cage, + (SELECT cp.row FROM ehr_lookups.cage_positions cp WHERE c.cage = cp.cage) as row, + (SELECT cp.columnIdx FROM ehr_lookups.cage_positions cp WHERE c.cage = cp.cage) as columnidx, + c.cage_type, + lc.cage as lowerCage, + lc.cage_type as lower_cage_type, + lc.divider, + CASE + WHEN lower(c.cage_type) = lower('No Cage') THEN 0 + WHEN NOT (SELECT d.countAsSeparate FROM ehr_lookups.divider_types d WHERE lc.divider = d.rowid) THEN 0 + ELSE 1 + END as isAvailable, + CASE + WHEN (c.status IS NOT NULL AND lower(c.status) = lower('Unavailable')) THEN 1 + ELSE 0 + END as isMarkedUnavailable + FROM ehr_lookups.cage c + LEFT JOIN ehr_lookups.cage lc ON (lower(lc.cage_type) <> lower('No Cage') AND c.room = lc.room AND (SELECT cp.row FROM ehr_lookups.cage_positions cp WHERE c.cage = cp.cage) = (SELECT cp.row FROM ehr_lookups.cage_positions cp WHERE lc.cage = cp.cage) AND ((SELECT cp.columnIdx FROM ehr_lookups.cage_positions cp WHERE c.cage = cp.cage) - 1) = (SELECT cp.columnIdx FROM ehr_lookups.cage_positions cp WHERE lc.cage = cp.cage) ); + + DELETE FROM onprc_ehr.availableCagesByRoom_temp; + + INSERT INTO onprc_ehr.availableCagesByRoom_temp(room, availableCages, markedUnavailable) + SELECT + c.room, + count(*) as availableCages, + sum(c.isMarkedUnavailable) as markedUnavailable + FROM onprc_ehr.availableCages_temp c + WHERE c.isAvailable = 1 + GROUP BY c.room; + + DELETE FROM onprc_ehr.roomUtilization_temp; + + INSERT INTO onprc_ehr.roomUtilization_temp(room, availableCages, CagesUsed, MarkedUnavailable, CagesEmpty, TotalAnimals) + SELECT + r.room, + max(cbr.availableCages) as AvailableCages, + count(DISTINCT h.cage) as CagesUsed, + max(cbr.markedUnavailable) as MarkedUnavailable, + max(cbr.availableCages) - count(DISTINCT h.cage) - max(cbr.markedUnavailable) as CagesEmpty, + count(DISTINCT h.participantid) as TotalAnimals + FROM ehr_lookups.rooms r + LEFT JOIN ( + SELECT c.room, c.cage + FROM ehr_lookups.cage c + WHERE cage IS NOT NULL + UNION ALL + SELECT r.room, NULL as cage + FROM ehr_lookups.rooms r + ) c ON (r.room = c.room) + LEFT JOIN studyDataset.c6d194_housing h ON (r.room=h.room AND (c.cage=h.cage OR (c.cage IS NULL AND h.cage IS NULL)) AND (((h.date <= now() AND h.enddate >= now()) OR (h.date <= now() AND h.enddate IS NULL)))) + LEFT JOIN onprc_ehr.availableCagesByRoom_temp cbr ON (cbr.room = r.room) + WHERE r.datedisabled IS NULL + GROUP BY r.room; +END; +$$ LANGUAGE plpgsql; + +CREATE TABLE onprc_ehr.PMIC_Reference_Data( + RowId SERIAL NOT NULL, + value varchar(1000) NULL, + name varchar(1000) NULL, + remark varchar(4000) NULL, + dateDisabled TIMESTAMP NULL, + created TIMESTAMP NULL, + createdBy int NULL, + modified TIMESTAMP NULL, + modifiedBy int NULL, + + CONSTRAINT pk_PMIC_Reference_Data PRIMARY KEY (RowId) +); + +CREATE TABLE onprc_ehr.ASB_SpecialInstructions( + value varchar(1000) NOT NULL, + remarks varchar(2000) NULL, + dateDisabled TIMESTAMP NULL, + created TIMESTAMP NULL, + createdBy int NULL, + modified TIMESTAMP NULL, + modifiedBy int NULL, + + CONSTRAINT pk_ASB_SpecialInstructions PRIMARY KEY (value) +); + +CREATE TABLE onprc_ehr.Prima_Animals( + Id int NOT NULL, + AlternateIdentifier varchar(63) NULL, + BreedId int NULL, + DateOfBirth TIMESTAMP NULL, + FecesId int NULL, + Gender smallint NOT NULL, + GeneTarget varchar(127) NULL, + GeneticLine varchar(127) NULL, + Genotype varchar(127) NULL, + Identifier varchar(127) NULL, + MannerOfDeathId int NULL, + RoomNumber varchar(9) NULL, + SpeciesId int NOT NULL, + StomachContentsId int NULL, + StrainId int NULL, + DateOfDeath TIMESTAMP NULL, + Created TIMESTAMPTZ NOT NULL, + OwnerId int NULL, + Perfuse BOOLEAN NOT NULL, + SampleType smallint NOT NULL +); + +CREATE TABLE onprc_ehr.Prima_TissueCollections( + Id int NOT NULL, + Constant smallint NULL, + IsWholeAnimal BOOLEAN NOT NULL, + SpeciesId int NOT NULL, + SpecimenType int NOT NULL, + CreatedByUserId int NOT NULL, + Deleted TIMESTAMPTZ NULL, + DeletedByUserId int NULL, + NextVersionId int NULL, + PreviousVersionId int NULL, + Title varchar(127) NOT NULL, + Created TIMESTAMPTZ NOT NULL, + LastModified TIMESTAMP DEFAULT now(), + Abbreviation varchar(127) NULL +); + +CREATE TABLE onprc_ehr.Prima_CaseBase( + Id int NOT NULL, + DifferentialDiagnosisId int NULL, + PathologistId int NULL, + PriorityLevelId int NOT NULL, + ResidentPathologistId int NULL, + SerialNumber int NOT NULL, + SurgeryDate TIMESTAMP NULL, + SurgicalWheelId int NOT NULL, + Created TIMESTAMPTZ NOT NULL, + ResearcherId int NULL, + StudyId int NULL, + Discriminator varchar(128) NULL, + StudyPhaseId int NULL, + CohortId int NULL, + SavedIdentifier text NULL, + Status smallint NOT NULL, + AlternateIdentifier varchar(24) NULL, + SurgeryLocationId int NULL, + ResearchPatientId int NULL, + AnimalId int NULL, + ClinicalPatientId int NULL, + SurgeryAge varchar(31) NULL +); + +CREATE TABLE onprc_ehr.Prima_CassetteBases( + Id bigint NOT NULL, + CassetteColorId int NOT NULL, + EmbeddingInstructionId int NOT NULL, + HasTissue BOOLEAN NOT NULL, + ProtocolCassetteId int NULL, + SpecimenBaseId bigint NOT NULL, + TissueCollectionId int NULL, + TissueProcessorProgramId int NULL, + TissueQuantity smallint NOT NULL, + CaseBaseId int NOT NULL, + PriorityLevelId int NOT NULL, + QcStatus smallint NOT NULL, + SurgicalSerialPart smallint NOT NULL, + Created TIMESTAMPTZ NOT NULL, + OrderedStatus smallint NOT NULL, + SavedIdentifier varchar(24) NULL, + BarcodeContent varchar(72) NULL, + AlternateIdentifier varchar(63) NULL, + PrintStatus smallint NOT NULL, + ItemStatus smallint NOT NULL, + Hazard smallint NOT NULL, + CurrentContainerId int NULL +); + +CREATE TABLE onprc_ehr.StudyDetails_RandalData( + id INT NOT NULL, + Rh varchar(100) NULL, + Cohort varchar(1000) NULL, + PI varchar(100) NULL, + Cohort_id INT NULL, + subcohort varchar(100) NULL, + grp varchar(100) NULL, + grp_order INT NULL, + grp_id INT NOT NULL, + rhCode varchar(100) NULL, + grpnm INT NULL, + Sex varchar(100) NULL, + cohortStart date NULL, + cohortEnd date NULL, + "do" date NULL, + DPC0 date NULL, + contprog varchar(100) NULL, + PIDO date NULL, + DPTO date NULL, + Birth date NULL, + Nx_date date NULL, + stims varchar(100) NULL, + active varchar(100) NULL, + CONSTRAINT pk_StudyDetails_Randal PRIMARY KEY (Id) +); + +CREATE TABLE onprc_ehr.BSUageclass +( + rowId SERIAL NOT NULL, + label varchar(255) NULL, + species varchar(255) NULL, + gender varchar(5) NULL, + ageclass INT NULL, + min double precision NULL, + max double precision NULL, + sort_order INT NULL, + dateDisabled TIMESTAMP NULL, + + CONSTRAINT PK_bsuageclass PRIMARY KEY (rowId) +); + +CREATE TABLE onprc_ehr.Epoc_tests +( + rowid SERIAL NOT NULL, + testid varchar(500) NOT NULL, + name varchar(500) NULL, + units varchar(50) NULL, + alias varchar(200) NULL, + alertOnAbnormal BOOLEAN NULL, + alertOnAny BOOLEAN NULL, + includeInPanel BOOLEAN NULL, + objectid ENTITYID NOT NULL, + sort_order int NULL, + container ENTITYID, + + CONSTRAINT PK_EpocTestsObject PRIMARY KEY (objectid) +); + +CREATE TABLE onprc_ehr.Reference_Data_IDkey +( + rowId SERIAL, + displayName varchar(4000) DEFAULT NULL, + idkey integer NOT NULL, + columnName varchar(1000) NOT NULL, + status integer NULL, + type varchar(500) NULL, + sort_order integer NULL, + created TIMESTAMP NOT NULL, + endDate TIMESTAMP DEFAULT NULL, + + CONSTRAINT pk_referenceIDkey PRIMARY KEY (idkey) +); + +CREATE OR REPLACE FUNCTION onprc_ehr.p_PopulateReferenceDataIDkey() RETURNS int AS $$ +BEGIN + TRUNCATE TABLE onprc_ehr.Reference_Data_IDkey RESTART IDENTITY; + + INSERT INTO onprc_ehr.Reference_Data_IDkey (displayName, idkey, columnName, status, type, sort_order, created, endDate) + SELECT + Name, + UserId, + 'Active_Groups', + CASE WHEN Active THEN 1 ELSE 0 END, + Type, + NULL, + now(), + NULL + FROM core.Principals + WHERE type = 'g' + AND UserId > 0 + AND Active IS TRUE + AND Container IS NULL; + + RETURN 0; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION onprc_ehr.p_CageStatusupdates() RETURNS int AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM ehr_lookups.cage) THEN + UPDATE ehr_lookups.cage + SET status = 'Normal' + WHERE status IS NULL; + END IF; + RETURN 0; +END; +$$ LANGUAGE plpgsql; + +CREATE TABLE onprc_ehr.CageAuditLog( + searchid INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 100) NOT NULL, + rowid int NULL, + location varchar(100) NULL, + room varchar(200) NULL, + cage varchar(200) NULL, + divider int NULL, + cage_type varchar(100) NULL, + hasTunnel BOOLEAN NULL, + status varchar(200) NULL, + Container ENTITYID NOT NULL, + area varchar(500) NULL, + housingtype varchar(500) NULL, + housingcondition varchar(500) NULL, + date_created TIMESTAMP NULL, + + CONSTRAINT pk_searchid PRIMARY KEY (searchid) +); + +CREATE OR REPLACE FUNCTION onprc_ehr.p_CageAuditHistoryProcess() RETURNS int AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM onprc_ehr.CageAuditLog) THEN + INSERT INTO onprc_ehr.CageAuditLog (rowid, location, room, cage, divider, cage_type, hasTunnel, status, container, area, housingtype, housingcondition, date_created) + SELECT + rowid, + a.location, + a.room, + a.cage, + a.divider, + a.cage_type, + a.hasTunnel, + a.status, + a.container, + (SELECT h.area FROM ehr_lookups.rooms h WHERE h.room = a.room) as area, + (SELECT s.value FROM ehr_lookups.rooms h, ehr_lookups.lookups s WHERE h.room = a.room AND s.rowid = h.housingtype) as housingtype, + (SELECT s.value FROM ehr_lookups.rooms h, ehr_lookups.lookups s WHERE h.room = a.room AND s.rowid = h.housingcondition) as housingcondition, + now() + FROM ehr_lookups.cage a; + END IF; + RETURN 0; +END; +$$ LANGUAGE plpgsql; + +CREATE TABLE onprc_ehr.Temp_ClnRemarks +( + date TIMESTAMP, + qcstate int, + participantid varchar(32), + project int, + remark varchar(250) , + p varchar(250) , + performedby varchar(250) , + category varchar(250) , + taskid varchar(4000), + createdby int, + modifiedby int +); + +CREATE TABLE onprc_ehr.Environmental_Reference_Data ( + rowId SERIAL, + label varchar(250) DEFAULT NULL, + value varchar(500) , + columnName varchar(255) NOT NULL, + sort_order integer NULL, + endDate TIMESTAMP DEFAULT NULL, + + CONSTRAINT pk_referenceenv PRIMARY KEY (value) +); + +CREATE TABLE onprc_ehr.Environmental_Assessment( + rowid INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 100) NOT NULL, + date TIMESTAMP NULL, + service_requested varchar(300) NULL, + charge_unit varchar(300) NULL, + testing_location varchar(300) NULL, + test_type varchar(300) NULL, + test_results varchar(100) NULL, + pass_fail varchar(100) NULL, + biological_Cycle varchar(300) NULL, + biological_BI varchar(300) NULL, + action varchar(300) NULL, + performedby varchar(300) NULL, + remarks varchar(300) NULL, + water_source varchar(300) NULL, + surface_tested varchar(300) NULL, + retest varchar(300) NULL, + colony_count varchar(300) NULL, + test_method varchar(300) NULL, + objectid ENTITYID NOT NULL, + createdby int NULL, + created TIMESTAMP NULL, + modifiedby int NULL, + modified TIMESTAMP NULL, + Container ENTITYID NOT NULL, + taskid entityid, + qcstate int NULL, + formsort int NULL, + + CONSTRAINT PK_assessment PRIMARY KEY (objectid) +); + +CREATE OR REPLACE FUNCTION onprc_ehr.p_Environmental_Update_Process() RETURNS int AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'list' AND table_name = 'c8754d723_surface_sanitation_minus_rodac_48hr') THEN + EXECUTE 'INSERT INTO onprc_ehr.Environmental_Assessment + (date, testing_location, service_requested, test_type, colony_count, pass_fail, performedby, action, remarks, objectid, created, createdby, modified, modifiedby, qcstate, container) + SELECT date, TestSite, ''Sanitation: Contact Plate'', TestType, ColonyCount, PassFail, CollectedBy, Action, comment, gen_random_uuid()::entityid, now(), 1896, now(), 1896, 18, ''98F39B23-5E3B-1037-AFE5-BD25D057100A''::entityid + FROM list.c8754d723_surface_sanitation_minus_rodac_48hr'; + END IF; + + IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'list' AND table_name = 'c8754d726_h2o_testing') THEN + EXECUTE 'INSERT INTO onprc_ehr.Environmental_Assessment + (date, testing_location, service_requested, water_source, test_type, test_results, pass_fail, remarks, objectid, created, createdby, modified, modifiedby, qcstate, container) + SELECT date, TestSite, ''Sanitation: Water Test'', H2OSource, TestType, result, PassFail, comment, gen_random_uuid()::entityid, now(), 1896, now(), 1896, 18, ''98F39B23-5E3B-1037-AFE5-BD25D057100A''::entityid + FROM list.c8754d726_h2o_testing'; + END IF; + + IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'list' AND table_name = 'c8754d795_biological_indicator_log') THEN + EXECUTE 'INSERT INTO onprc_ehr.Environmental_Assessment + (date, testing_location, service_requested, biological_Cycle, biological_BI, pass_fail, retest, action, performedby, remarks, objectid, created, createdby, modified, modifiedby, qcstate, container) + SELECT date, autoclave, ''Sanitation: Bio-indicator'', "cycle (if applicable)", "BI# (for ASA)", "Pass / Fail", "Results Read by", action, "Collected By", comment, gen_random_uuid()::entityid, now(), 1896, now(), 1896, 18, ''98F39B23-5E3B-1037-AFE5-BD25D057100A''::entityid + FROM list.c8754d795_biological_indicator_log'; + END IF; + + IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'list' AND table_name = 'c8754d731_atp_testing') THEN + EXECUTE 'INSERT INTO onprc_ehr.Environmental_Assessment + (date, performedby, service_requested, testing_location, surface_tested, pass_fail, remarks, retest, test_results, action, objectid, created, createdby, modified, modifiedby, qcstate, container) + SELECT date, Tech_Initials, ''Sanitation: ATP'', area, Surface, initial, comments, retest, Lab_Group, location, gen_random_uuid()::entityid, now(), 1896, now(), 1896, 18, ''98F39B23-5E3B-1037-AFE5-BD25D057100A''::entityid + FROM list.c8754d731_atp_testing'; + END IF; + + RETURN 0; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION onprc_ehr.p_EnvironmentalHistoricalUpdates() RETURNS int AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM onprc_ehr.Environmental_Assessment) THEN + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL SW' WHERE lower(testing_location) = lower('Col. SW'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 1', charge_unit = 'Clinpath' WHERE lower(testing_location) = lower('Annex Rm 1'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL SW', charge_unit = 'Clinpath' WHERE lower(testing_location) = lower('Colony SW'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Catch Area 2', charge_unit = 'Clinpath' WHERE lower(testing_location) = lower('Catch 2'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 1 Lixit' WHERE lower(testing_location) = lower('Pens Run 1'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 10 Lixit' WHERE lower(testing_location) = lower('Pens Run 10'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 11 Lixit' WHERE lower(testing_location) = lower('Pens Run 11'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 12 Lixit' WHERE lower(testing_location) = lower('Pens Run 12'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 2 Lixit' WHERE lower(testing_location) = lower('Pens Run 2'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 3 Lixit' WHERE lower(testing_location) = lower('Pens Run 3'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 4 Lixit' WHERE lower(testing_location) = lower('Pens Run 4'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 5 Lixit' WHERE lower(testing_location) = lower('Pens Run 5'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 6 Lixit' WHERE lower(testing_location) = lower('Pens Run 6'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 7 Lixit' WHERE lower(testing_location) = lower('Pens Run 7'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 8 Lixit' WHERE lower(testing_location) = lower('Pens Run 8'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens Run 9 Lixit' WHERE lower(testing_location) = lower('Pens Run 9'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 1 Lixit' WHERE lower(testing_location) = lower('SGH 1'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 10 Lixit' WHERE lower(testing_location) = lower('SGH 10'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 11 Lixit' WHERE lower(testing_location) = lower('SGH 11'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 12 Lixit' WHERE lower(testing_location) = lower('SGH 12'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 13 Lixit' WHERE lower(testing_location) = lower('SGH 13'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 14 Lixit' WHERE lower(testing_location) = lower('SGH 14'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 15 Lixit' WHERE lower(testing_location) = lower('SGH 15'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 16 Lixit' WHERE lower(testing_location) = lower('SGH 16'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 17 Lixit' WHERE lower(testing_location) = lower('SGH 17'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 18 Lixit' WHERE lower(testing_location) = lower('SGH 18'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 19 Lixit' WHERE lower(testing_location) = lower('SGH 19'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 2 Lixit' WHERE lower(testing_location) = lower('SGH 2'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 20 Lixit' WHERE lower(testing_location) = lower('SGH 20'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 21 Lixit' WHERE lower(testing_location) = lower('SGH 21'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 22 Lixit' WHERE lower(testing_location) = lower('SGH 22'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 23 Lixit' WHERE lower(testing_location) = lower('SGH 23'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 24 Lixit' WHERE lower(testing_location) = lower('SGH 24'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 25 Lixit' WHERE lower(testing_location) = lower('SGH 25'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 26 Lixit' WHERE lower(testing_location) = lower('SGH 26'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 27 Lixit' WHERE lower(testing_location) = lower('SGH 27'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 28 Lixit' WHERE lower(testing_location) = lower('SGH 28'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 29 Lixit' WHERE lower(testing_location) = lower('SGH 29'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 30 Lixit' WHERE lower(testing_location) = lower('SGH 30'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 3 Lixit' WHERE lower(testing_location) = lower('SGH 3'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 31 Lixit' WHERE lower(testing_location) = lower('SGH 31'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 32 Lixit' WHERE lower(testing_location) = lower('SGH 32'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 4 Lixit' WHERE lower(testing_location) = lower('SGH 4'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 5 Lixit' WHERE lower(testing_location) = lower('SGH 5'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 6 Lixit' WHERE lower(testing_location) = lower('SGH 6'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 7 Lixit' WHERE lower(testing_location) = lower('SGH 7'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 8 Lixit' WHERE lower(testing_location) = lower('SGH 8'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 9 Lixit' WHERE lower(testing_location) = lower('SGH 9'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'BOS RM 102' WHERE lower(testing_location) = lower('Bosky 102'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'BOS RM 103' WHERE lower(testing_location) = lower('Bosky 103'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'BOS RM 104' WHERE lower(testing_location) = lower('Bosky 104'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'BOS RM 122' WHERE lower(testing_location) = lower('Bosky 122'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'BOS RM 123' WHERE lower(testing_location) = lower('Bosky 123'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Cage Washer Colony Annex toy' WHERE lower(testing_location) = lower('Cage Washer Colony Annex tunnel toy'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Cage Washer VGTI Large (Jan/June)' WHERE lower(testing_location) = lower('Cage Washer VGTI Large (semi-annual)'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Cage Washer VGTI Small (Jan/June)' WHERE lower(testing_location) = lower('Cage Washer VGTI Small (semi-annual)'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Dishwasher Colony North' WHERE lower(testing_location) = lower('Dishwasher N. Colony'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Dishwasher Colony South' WHERE lower(testing_location) = lower('Dishwasher S. Colony'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 37' WHERE lower(testing_location) = lower('Annex room 37'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Catch Area 2' WHERE lower(testing_location) = lower('Catch 2'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Catch Area 5' WHERE lower(testing_location) = lower('Catch 5'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL SW' WHERE lower(testing_location) = lower('Col. SW'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL NW' WHERE lower(testing_location) = lower('Col. NW'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL NW' WHERE lower(testing_location) = lower('Colony NW'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL RM 4' WHERE lower(testing_location) = lower('Colony RM 4'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL Run 1' WHERE lower(testing_location) = lower('Colony Run 1'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL Run 2' WHERE lower(testing_location) = lower('Colony Run 2'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL Run 3' WHERE lower(testing_location) = lower('Colony Run 3'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL Run 4' WHERE lower(testing_location) = lower('Colony Run 4'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL Run 5' WHERE lower(testing_location) = lower('Colony Run 5'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL Run 6' WHERE lower(testing_location) = lower('Colony Run 6'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL Run 7' WHERE lower(testing_location) = lower('Colony Run 7'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL Run 8' WHERE lower(testing_location) = lower('Colony Run 8'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'COL SW' WHERE lower(testing_location) = lower('Colony SW'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 1' WHERE lower(testing_location) = lower('SGH 1 inside'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 1' WHERE lower(testing_location) = lower('SGH 1 inside'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 2' WHERE lower(testing_location) = lower('SGH 2 outside'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 2' WHERE lower(testing_location) = lower('SGH 2 outside'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 29' WHERE lower(testing_location) = lower('SGH 29 inside'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 29' WHERE lower(testing_location) = lower('SGH 29 inside'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 30' WHERE lower(testing_location) = lower('SGH 30 outside'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'SGH 30' WHERE lower(testing_location) = lower('SGH 30 outside'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Dishwasher Bldg 611 ' WHERE lower(testing_location) = lower('SGH 30 outside'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Dishwasher ASA 135' WHERE lower(testing_location) = lower('Dishwasher ASA 135 '); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Dishwasher ASA 136' WHERE lower(testing_location) = lower('Dishwasher ASA 136 '); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Dishwasher Bldg 611' WHERE lower(testing_location) = lower('Dishwasher Bldg 611 '); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 1' WHERE lower(testing_location) = lower('AN RM 1'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 34' WHERE lower(testing_location) = lower('AN RM 34'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 13' WHERE lower(testing_location) = lower('AN RM 13'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 14' WHERE lower(testing_location) = lower('AN RM 14'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 15' WHERE lower(testing_location) = lower('AN RM 15'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 16' WHERE lower(testing_location) = lower('AN RM 16'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 2' WHERE lower(testing_location) = lower('AN RM 2'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 34' WHERE lower(testing_location) = lower('AN RM 34'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 39' WHERE lower(testing_location) = lower('AN RM 39'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Rm 4' WHERE lower(testing_location) = lower('AN RM 4'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Run 1' WHERE lower(testing_location) = lower('AN RUN 1'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Run 2' WHERE lower(testing_location) = lower('AN RUN 2'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Run 3' WHERE lower(testing_location) = lower('AN RUN 3'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Annex Run 30' WHERE lower(testing_location) = lower('AN RUN 30'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Col Run 7E' WHERE lower(testing_location) = lower('Col Run 7 E'); + + UPDATE onprc_ehr.Environmental_Assessment + SET charge_unit = 'Clinpath' + WHERE lower(testing_location) IN (SELECT DISTINCT lower(value) FROM onprc_ehr.Environmental_Reference_Data WHERE lower(columnname) = lower('testlocation')); + + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Col Run 7A' WHERE lower(testing_location) = lower('Col Run 7 A'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Col Run 7B' WHERE lower(testing_location) = lower('Col Run 7 B'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Col Run 7D' WHERE lower(testing_location) = lower('Col Run 7 D'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Colony Rm 2 (Clinic)' WHERE lower(testing_location) = lower('Colony Rm 2 Clinic'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens RM 102A (Clinic)' WHERE lower(testing_location) = lower('Pens Rm 102A (Clinic)'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens RM 104 (Feed)' WHERE lower(testing_location) = lower('PENS Rm 104 (Feed Room)'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Pens RM 104 (Feed)' WHERE lower(testing_location) = lower('Pens RM 104 (Feed )'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'VGTI 0120 (clean cage wash)' WHERE lower(testing_location) = lower('VGTI 0120 (clean cage wash'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Col Run 6A' WHERE lower(testing_location) = lower('Col Run 6 A'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Col Run 6C' WHERE lower(testing_location) = lower('Col Run 6 C'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'ASB 3 Cage Wash' WHERE lower(testing_location) = lower('ASB 3 Cage Wash Area'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'ASB 1 Cage Wash' WHERE lower(testing_location) = lower('ASB 1 Cage Wash Area'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Cage Washer ASB 1 cage' WHERE lower(testing_location) = lower('Cage Washer ASB 1'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Cage Washer VGTI Large (Jan/June)' WHERE lower(testing_location) = lower('Cage Washer VGTI Large'); + UPDATE onprc_ehr.Environmental_Assessment SET testing_location = 'Cage Washer VGTI Small (Jan/June)' WHERE lower(testing_location) = lower('Cage Washer VGTI Small'); + END IF; + + RETURN 0; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION onprc_ehr.MPA_ClnRemarkAddition() RETURNS void AS $$ +DECLARE + -- v_ prefix avoids the same-named dataset columns below: plpgsql errors on an unqualified name that matches both a variable and a column. + v_MPACount Int; + v_taskId varchar(4000); + v_displayName varchar(250); +BEGIN + DELETE FROM onprc_ehr.Temp_ClnRemarks; + + SELECT COUNT(*) INTO v_MPACount FROM studyDataset.c6d178_drug + WHERE lower(code) = lower('E-85760') AND date::date = now()::date AND qcstate = 18; + + IF v_MPACount > 0 THEN + SELECT u.displayName INTO v_displayName FROM core.users u WHERE u.userid = 1003; + + v_taskId := gen_random_uuid(); + + INSERT INTO ehr.tasks + (taskid, category, title, formtype, qcstate, assignedto, duedate, createdby, created, + container, modifiedby, modified, description, datecompleted) + VALUES + (v_taskId, 'Task', 'Bulk Clinical Entry', 'Bulk Clinical Entry', 18, 1003, now(), 1003, now(), + 'CD17027B-C55F-102F-9907-5107380A54BE'::entityid, 1003, now(), 'Created by the ETL process', now()); + + INSERT INTO onprc_ehr.Temp_ClnRemarks ( + date, qcstate, participantid, project, remark, p, performedby, category, taskid, createdby, modifiedby + ) + SELECT now(), 18, participantid, project, 'Remark entered by the ETL process', 'MPA injection administered', v_displayName, 'Clinical', v_taskId, 1003, 1003 + FROM studyDataset.c6d178_drug + WHERE lower(code) = lower('E-85760') AND date::date = now()::date AND qcstate = 18; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE TABLE onprc_ehr.TB_TestTemp( + rowid INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 100) NOT NULL, + animalid varchar(200) NULL, + date TIMESTAMP NULL, + objectid ENTITYID NOT NULL, + created TIMESTAMP NULL, + createdby integer NULL, + performedby varchar(200) NULL +); + +CREATE TABLE onprc_ehr.TB_TestTempMaster( + rowid integer , + animalid varchar(200) NULL, + date TIMESTAMP NULL, + objectid ENTITYID NOT NULL, + created TIMESTAMP NULL, + createdby integer NULL, + performedby varchar(200) NULL +); + +CREATE OR REPLACE FUNCTION onprc_ehr.p_Create_TB_Observationrecords() RETURNS int AS $$ +DECLARE + r RECORD; + taskId varchar(4000); + runId varchar(4000); + obsDate TIMESTAMP; +BEGIN + TRUNCATE TABLE onprc_ehr.TB_TestTemp RESTART IDENTITY; + + INSERT INTO onprc_ehr.TB_TestTemp (animalid, date, objectid, created, createdby, performedby) + SELECT + a.participantid, + a.date, + a.objectid, + a.created, + a.createdBy, + a.performedby + FROM studydataset.c6d214_encounters a + WHERE a.participantid NOT IN ( + SELECT b.participantid + FROM studydataset.c6d171_clinical_observations b + WHERE a.participantid = b.participantid + AND b.date::date = (a.date::date + INTERVAL '3 days')::date + AND lower(b.category) = lower('TB TST Score (72 hr)') + AND a.created >= now()::date + AND lower(a.type) = lower('Procedure') + AND a.qcstate = 18 + AND a.procedureid = 802 + ) + AND lower(a.type) = lower('Procedure') + AND a.qcstate = 18 + AND a.procedureid = 802 + AND a.created >= now()::date + AND a.participantid IN ( + SELECT k.participantid + FROM studydataset.c6d203_demographics k + WHERE lower(k.calculated_status) = lower('Alive') + ) + ORDER BY a.participantid, a.date DESC; + + IF NOT EXISTS (SELECT 1 FROM onprc_ehr.TB_TestTemp) THEN + RETURN 0; + END IF; + + taskId := gen_random_uuid(); + + INSERT INTO EHR.Tasks ( + taskid, description, title, qcstate, formType, category, container, assignedto, created, createdby, modified, modifiedby + ) + VALUES ( + taskId, + 'TB TST Scores ' || COALESCE(obsDate::text, ''), -- TODO: Change from SQL Server to not output NULL + 'TB TST Scores', + 20, + 'TB TST Scores', + 'task', + 'CD17027B-C55F-102F-9907-5107380A54BE'::entityid, + 1822, + now(), + 1042, + now(), + 1042 + ); + + FOR r IN SELECT * FROM onprc_ehr.TB_TestTemp LOOP + obsDate := r.date + INTERVAL '3 days'; + + IF NOT EXISTS ( + SELECT 1 FROM studydataset.c6d171_clinical_observations j + WHERE j.participantid = r.animalid + AND j.date::date = obsDate::date + AND lower(j.category) = lower('TB TST Score (72 hr)') + ) THEN + runId := gen_random_uuid(); + + INSERT INTO studydataset.c6d171_clinical_observations ( + participantid, date, category, area, observation, created, createdby, performedby, objectid, taskid, qcstate, modified, modifiedby, lsid + ) + VALUES ( + r.animalid, + obsDate, + 'TB TST Score (72 hr)', + 'Right Eyelid', + 'Grade: Negative', + now(), + r.createdby, + r.performedby, + runId, + taskId, + 20, + now(), + r.createdby, + 'urn:lsid:ohsu.edu:Study.Data-6:5006.10003.19810204.0000.' || runId + ); + END IF; + END LOOP; + + INSERT INTO onprc_ehr.TB_TestTempMaster (rowid, animalid, date, objectid, created, createdby, performedby) + SELECT rowid, animalid, date, objectid, created, createdby, performedby + FROM onprc_ehr.TB_TestTemp; + + RETURN 0; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION onprc_ehr.BaseProtocol() RETURNS void AS $$ +BEGIN + WITH BaseProtocol_CTE AS ( + SELECT + RowID, + Protocol_id, + CASE + WHEN LENGTH(Protocol_id) > 10 THEN SUBSTRING(Protocol_id, 6, 15) + ELSE Protocol_id + END AS BaseProtocolVal, + CASE + WHEN LENGTH(Protocol_id) > 10 THEN SUBSTRING(Protocol_id, 1, 5) + ELSE 'Original' + END AS RevisionNumberVal + FROM onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS + ) + UPDATE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS p + SET BaseProtocol = bp.BaseProtocolVal, + RevisionNumber = bp.RevisionNumberVal + FROM BaseProtocol_CTE bp + WHERE p.RowID = bp.RowID; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION onprc_ehr.ExpiredProtocolUpdate() RETURNS void AS $$ +BEGIN + WITH ApprovedProtocols AS ( + SELECT + BaseProtocol, + MAX(Approval_Date) AS maxApprovalDate + FROM + onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS + WHERE + lower(Protocol_State) IN (lower('Approved'), lower('Expired'), lower('Terminated')) + GROUP BY + BaseProtocol + ), + DistinctProtocols AS ( + SELECT DISTINCT + p.rowID, + p.BaseProtocol, + p.RevisionNumber, + p.Protocol_State, + p.Approval_Date, + p.Last_Modified, + p.Three_Year_Expiration + FROM + onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS p + INNER JOIN ApprovedProtocols ap ON p.BaseProtocol = ap.BaseProtocol + AND p.Approval_Date = ap.maxApprovalDate + ), + ExpiredProtocol AS ( + SELECT + d.*, + p.protocol, + p.enddate + FROM DistinctProtocols d + INNER JOIN ehr.protocol p ON d.BaseProtocol = p.external_ID + WHERE lower(d.Protocol_State) <> lower('Approved') AND p.enddate IS NULL + ) + UPDATE ehr.protocol p + SET enddate = now() + FROM ExpiredProtocol e + WHERE p.external_id = e.BaseProtocol; +END; +$$ LANGUAGE plpgsql; + +CREATE TABLE onprc_ehr.procedure_default_blood ( + rowid SERIAL, + procedureid int, + sampletype varchar(300) NULL, + additionalServices varchar(1000) NULL, + reason varchar(300) NULL, + instructions varchar(2000) NULL, + chargetype varchar(400) NULL, + + CONSTRAINT PK_procedure_default_blood PRIMARY KEY (rowid) +); + +CREATE TABLE onprc_ehr.Rpt_AnimalID_Weights( + searchid INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 100) NOT NULL, + animalID varchar(100) NULL, + date TIMESTAMP NULL, + weight decimal(12,5) NULL, + taskId ENTITYID NULL, + created TIMESTAMP NULL, + createdby smallint NULL, + modified TIMESTAMP NULL, + modifiedby smallint NULL +); + +CREATE TABLE onprc_ehr.Rpt_AnimalID_WeightsMaster( + searchid INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 100) NOT NULL, + rowid int, + animalID varchar(100) NULL, + date TIMESTAMP NULL, + weight decimal(12,5) NULL, + taskId ENTITYID NULL, + created TIMESTAMP NULL, + createdby smallint NULL, + modified TIMESTAMP NULL, + modifiedby smallint NULL, + actual_created TIMESTAMP NULL, + remark varchar(1000) NULL +); + +CREATE OR REPLACE FUNCTION onprc_ehr.sp_PathologyTissueWeightsProcess( + -- v_ prefix avoids the tissue_samples.enddate column below: plpgsql errors on an unqualified name that matches both a parameter and a column. + v_StartDate TIMESTAMP, + v_EndDate TIMESTAMP +) RETURNS int AS $$ +DECLARE + r RECORD; + runId varchar(4000); +BEGIN + DELETE FROM onprc_ehr.Rpt_AnimalID_Weights; + + INSERT INTO onprc_ehr.Rpt_AnimalID_Weights (animalID, date, weight, taskId, created, createdby, modified, modifiedby) + SELECT + e.participantid, + e.date, + e.weight, + e.taskid, + e.created, + e.createdby, + e.modified, + e.modifiedby + FROM studydataset.c6d174_tissue_samples e + WHERE lower(e.tissue) = lower('T-00010') + AND e.date >= v_StartDate + AND e.date < (v_EndDate + INTERVAL '1 day') + AND e.qcstate = 18 + AND e.weight IS NOT NULL + ORDER BY date DESC; + + FOR r IN SELECT * FROM onprc_ehr.Rpt_AnimalID_Weights LOOP + IF NOT EXISTS ( + SELECT 1 FROM studydataset.c6d175_weight + WHERE participantid = r.animalID AND date = r.date + ) THEN + runId := gen_random_uuid(); + + INSERT INTO studydataset.c6d175_weight ( + participantid, date, weight, qcstate, created, createdby, modified, modifiedby, taskid, objectid, remark, lsid + ) + VALUES ( + r.animalID, + r.date, + r.weight / 1000.0, + 18, + r.created, + r.createdby, + r.modified, + r.modifiedby, + r.taskId, + runId, + 'Weight added from Path Tissue records', + 'urn:lsid:ohsu.edu:Study.Data-6:1045.' || r.animalID || '.' || to_char(r.date::date, 'YYYYMMDD') || '.0000.' || runId -- TODO: SQL Server hard-coded LSID had a leading space. Maybe need to preserve that here? + ); + END IF; + END LOOP; + + INSERT INTO onprc_ehr.Rpt_AnimalID_WeightsMaster (rowid, animalID, date, weight, taskId, created, createdby, modified, modifiedby, actual_created, remark) + SELECT searchid, animalID, date, weight, taskId, created, createdby, modified, modifiedby, now(), 'Pathology Tissue Weight entry' + FROM onprc_ehr.Rpt_AnimalID_Weights; + + RETURN 0; +END; +$$ LANGUAGE plpgsql; + +CREATE TABLE onprc_ehr.Rpt_AnimalIDTissues( + Searchkey SERIAL NOT NULL, + animalID varchar(100) NULL, + date TIMESTAMP NULL +); + +CREATE TABLE onprc_ehr.Rpt_AnimalIDTissues_Master( + rowid SERIAL NOT NULL, + SearchID int NULL, + animalID varchar(100) NULL, + date TIMESTAMP NULL, + actual_Created TIMESTAMP NULL, + remarks varchar(500) +); + +CREATE OR REPLACE FUNCTION onprc_ehr.sp_RptNecropsyTissueDistributionUpdates( + StartDate TIMESTAMP, + EndDate TIMESTAMP +) RETURNS int AS $$ +DECLARE + r RECORD; + -- v_ prefix avoids the tissuedistributions.taskid column below: plpgsql errors on an unqualified name that matches both a variable and a column. + v_taskId varchar(4000); +BEGIN + DELETE FROM onprc_ehr.Rpt_AnimalIDTissues; + + INSERT INTO onprc_ehr.Rpt_AnimalIDTissues (animalID, date) + SELECT DISTINCT + e.participantid, + e.date + FROM studydataset.c6d265_tissuedistributions e + WHERE e.date >= StartDate + AND e.date < (EndDate + INTERVAL '1 day') + AND e.qcstate = 18 + ORDER BY e.participantid, e.date; + + FOR r IN SELECT * FROM onprc_ehr.Rpt_AnimalIDTissues LOOP + v_taskId := gen_random_uuid(); + + INSERT INTO EHR.Tasks ( + taskid, description, title, qcstate, formType, category, container, assignedto, created, createdby, modified, modifiedby + ) + VALUES ( + v_taskId, + 'Path Tissues ' || COALESCE(r.date::text, ''), + 'PathologyTissues', + 18, + 'PathologyTissues', + 'task', + 'CD17027B-C55F-102F-9907-5107380A54BE'::entityid, + 1693, + now(), + 1042, + now(), + 1042 + ); + + UPDATE studydataset.c6d265_tissuedistributions + SET taskid = v_taskId + WHERE participantid = r.animalID AND date = r.date; + END LOOP; + + INSERT INTO onprc_ehr.Rpt_AnimalIDTissues_Master (SearchID, animalID, date, actual_Created, remarks) + SELECT Searchkey, animalID, date, now(), 'Tissue Distribution entries' + FROM onprc_ehr.Rpt_AnimalIDTissues; + + RETURN 0; +END; +$$ LANGUAGE plpgsql; + +CREATE TABLE onprc_ehr.snomed_counter +( + subset varchar(255) NOT NULL, + count integer NOT NULL, + prefix varchar(10) NOT NULL, + container entityid, + createdby userid, + created TIMESTAMP, + modifiedby userid, + modified TIMESTAMP, + + CONSTRAINT pk_snomed_counter PRIMARY KEY (subset), + CONSTRAINT fk_onprc_snomed_counter_container FOREIGN KEY (container) REFERENCES core.Containers (EntityId) +); + +CREATE TABLE onprc_ehr.CenterProjectsTemp( + searchid INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 100) NOT NULL, + project smallint NULL, + protocol varchar(400) NULL, + account varchar(1000) NULL, + title varchar(2000) NULL, + research smallint NULL, + createdby smallint NULL, + created TIMESTAMP NULL, + modified TIMESTAMP NULL, + modifiedby smallint NULL, + startdate TIMESTAMP NULL, + enddate TIMESTAMP NULL, + displayname varchar(1000) NULL, + investigatorid smallint NULL, + use_category varchar(500) NULL, + projecttype varchar(500) NULL, + objectid text NULL, + date_posted TIMESTAMP NULL +); + +CREATE OR REPLACE FUNCTION onprc_ehr.p_CenterProjectsHistoricalProcess( + InitialDate TIMESTAMP +) RETURNS int AS $$ +BEGIN + IF (now()::date = InitialDate::date) THEN + INSERT INTO onprc_ehr.CenterProjectsTemp ( + project, protocol, account, title, research, createdby, created, modified, modifiedby, startdate, enddate, displayname, investigatorid, use_category, projecttype, objectid, date_posted + ) + SELECT + project, + protocol::varchar(400), + account, + title, + research::int, -- boolean on PostgreSQL, bit on SQL Server; no implicit cast to the smallint target + createdby, + created, + modified, + modifiedby, + startdate, + enddate, + name, + investigatorid, + use_category, + projecttype, + objectid, + now() + FROM ehr.project + WHERE (enddate IS NULL OR enddate >= now()) + ORDER BY modified; + END IF; + + IF EXISTS ( + SELECT 1 FROM ehr.project + WHERE (enddate IS NULL OR enddate >= now()) AND modified >= now()::date + ) THEN + INSERT INTO onprc_ehr.CenterProjectsTemp ( + project, protocol, account, title, research, createdby, created, modified, modifiedby, startdate, enddate, displayname, investigatorid, use_category, projecttype, objectid, date_posted + ) + SELECT + project, + protocol::varchar(400), + account, + title, + research::int, + createdby, + created, + modified, + modifiedby, + startdate, + enddate, + name, + investigatorid, + use_category, + projecttype, + objectid, + now() + FROM ehr.project + WHERE (enddate IS NULL OR enddate >= now()) AND modified >= now()::date + ORDER BY modified; + END IF; + + RETURN 0; +END; +$$ LANGUAGE plpgsql; + +CREATE TABLE onprc_ehr.pairing_observation_types ( + rowid INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 100) NOT NULL, + value varchar(200), + category varchar(200), + editorconfig text, + schemaname varchar(200), + queryname varchar(200), + valuecolumn varchar(200), + Created TIMESTAMP, + CreatedBy USERID, + Modified TIMESTAMP, + ModifiedBy USERID, + Container entityId NOT NULL, + + CONSTRAINT PK_ONPRC_EHR_PAIRING_OBSERVATION_TYPES PRIMARY KEY (rowid) +); + +CREATE OR REPLACE FUNCTION onprc_ehr.p_BirthGeographicOriginUpdates() RETURNS int AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM studydataset.c6d202_birth bir + JOIN studydataset.c6d512_geneticancestry b ON bir.participantid = b.participantid + WHERE b.enddate IS NULL + AND bir.qcstate = 18 + AND b.qcstate = 18 + AND bir.geographic_origin <> b.result + AND b.result IS NOT NULL + ) THEN + UPDATE studydataset.c6d202_birth bir + SET geographic_origin = b.result, + modified = now(), + modifiedby = b.modifiedby + FROM studydataset.c6d512_geneticancestry b + WHERE bir.participantid = b.participantid + AND b.enddate IS NULL + AND bir.qcstate = 18 + AND b.qcstate = 18 + AND bir.geographic_origin <> b.result + AND b.result IS NOT NULL; + END IF; + + RETURN 0; +END; +$$ LANGUAGE plpgsql; diff --git a/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-25.002-25.003.sql b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-25.002-25.003.sql new file mode 100644 index 000000000..b7a569477 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-25.002-25.003.sql @@ -0,0 +1,161 @@ +CREATE FUNCTION audit.ArchiveAuditTables( + -- Name must match the declared by the ArchiveAuditLogs ETL; LabKey binds + -- stored procedure parameters by name, so a prefixed name would silently arrive NULL. + INOUT RetentionMonths INT +) +LANGUAGE plpgsql +AS $$ +DECLARE + -- Configuration variables + v_SourceSchema VARCHAR(128) := 'audit'; + v_DestLogSchema VARCHAR(128) := 'labkey_audit'; + v_DestTableSchema VARCHAR(128) := 'labkey_audit_audit'; + + -- Operational variables + v_CutoffDate TIMESTAMP; + v_CurrentTable RECORD; + v_CreatedCol VARCHAR(128); + v_LogID INT; + v_ColumnList TEXT; + v_SQL TEXT; + v_RecordsInserted INT; + v_RecordsDeleted INT; + v_ErrorMessage TEXT; +BEGIN + -- Calculate Retention Months + RetentionMonths := CASE WHEN RetentionMonths - 6 > 12 THEN RetentionMonths - 6 ELSE 12 END; + RAISE NOTICE 'Archiving audit logs older than % months old', RetentionMonths; + + v_CutoffDate := CURRENT_TIMESTAMP - (RetentionMonths || ' months')::INTERVAL; + + -- Validate if source schema exists + IF NOT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = v_SourceSchema) THEN + RAISE EXCEPTION 'Source schema "%" does not exist.', v_SourceSchema; + END IF; + + -- Ensure destination schemas exist + EXECUTE format('CREATE SCHEMA IF NOT EXISTS %I', v_DestLogSchema); + EXECUTE format('CREATE SCHEMA IF NOT EXISTS %I', v_DestTableSchema); + + -- Create ArchiveAuditLog table if not exists + EXECUTE format(' + CREATE TABLE IF NOT EXISTS %I.ArchiveAuditLog ( + LogID INT GENERATED BY DEFAULT AS IDENTITY, + TableName VARCHAR(128) NOT NULL, + Operation VARCHAR(50) NOT NULL, + StartTime TIMESTAMP NOT NULL, + EndTime TIMESTAMP NULL, + Status VARCHAR(50) NULL, + RecordsProcessed INT NULL, + ErrorMessage TEXT NULL, + RetentionMonths INT NULL, + CONSTRAINT PK_ArchiveAuditLog PRIMARY KEY (LogID) + )', v_DestLogSchema); + + -- Create RetentionMonths column in ArchiveAuditLog table if it does not exist + EXECUTE format(' + ALTER TABLE %I.ArchiveAuditLog + ADD COLUMN IF NOT EXISTS RetentionMonths INT NULL', v_DestLogSchema); + + -- Loop through all base tables in the source schema + FOR v_CurrentTable IN + SELECT table_name + FROM information_schema.tables + WHERE table_schema = v_SourceSchema + AND table_type = 'BASE TABLE' + LOOP + -- Find the exact name of the 'Created' column (case-insensitive check) + SELECT column_name + FROM information_schema.columns + WHERE table_schema = v_SourceSchema + AND table_name = v_CurrentTable.table_name + AND lower(column_name) = 'created' + LIMIT 1 + INTO v_CreatedCol; + + -- If 'Created' column is not found, skip this table + IF v_CreatedCol IS NULL THEN + RAISE WARNING 'Table %.% does not have a "Created" column. Skipping.', v_SourceSchema, v_CurrentTable.table_name; + CONTINUE; + END IF; + + -- Insert log record and get LogID + v_SQL := format(' + INSERT INTO %I.ArchiveAuditLog (TableName, Operation, StartTime, Status, RetentionMonths) + VALUES ($1, ''Archive'', CURRENT_TIMESTAMP, ''Started'', $2) + RETURNING LogID', v_DestLogSchema); + EXECUTE v_SQL USING v_CurrentTable.table_name, RetentionMonths INTO v_LogID; + + -- Subtransaction block to handle errors per table + BEGIN + -- Create destination table if it does not exist + IF NOT EXISTS ( + SELECT 1 FROM information_schema.tables + WHERE table_schema = v_DestTableSchema + AND table_name = v_CurrentTable.table_name + ) THEN + v_SQL := format('CREATE TABLE %I.%I AS SELECT * FROM %I.%I WHERE 1 = 0', + v_DestTableSchema, v_CurrentTable.table_name, + v_SourceSchema, v_CurrentTable.table_name); + EXECUTE v_SQL; + END IF; + + -- Get column list excluding identity and serial columns + SELECT string_agg(quote_ident(a.attname), ', ') + FROM pg_attribute a + JOIN pg_class t ON a.attrelid = t.oid + JOIN pg_namespace s ON t.relnamespace = s.oid + LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum + WHERE s.nspname = v_SourceSchema + AND t.relname = v_CurrentTable.table_name + AND a.attnum > 0 + AND NOT a.attisdropped + AND a.attidentity = '' + AND (d.adbin IS NULL OR pg_get_expr(d.adbin, d.adrelid) NOT LIKE 'nextval%') + INTO v_ColumnList; + + IF v_ColumnList IS NULL OR v_ColumnList = '' THEN + RAISE EXCEPTION 'No valid columns found to archive for table %', v_CurrentTable.table_name; + END IF; + + -- Archive rows to destination table + v_SQL := format('INSERT INTO %I.%I (%s) SELECT %s FROM %I.%I WHERE %I < $1', + v_DestTableSchema, v_CurrentTable.table_name, v_ColumnList, v_ColumnList, + v_SourceSchema, v_CurrentTable.table_name, v_CreatedCol); + EXECUTE v_SQL USING v_CutoffDate; + GET DIAGNOSTICS v_RecordsInserted = ROW_COUNT; + + -- Delete archived rows from source table + v_SQL := format('DELETE FROM %I.%I WHERE %I < $1', + v_SourceSchema, v_CurrentTable.table_name, v_CreatedCol); + EXECUTE v_SQL USING v_CutoffDate; + GET DIAGNOSTICS v_RecordsDeleted = ROW_COUNT; + + -- Update log record on success + v_SQL := format(' + UPDATE %I.ArchiveAuditLog + SET RecordsProcessed = $1, + EndTime = CURRENT_TIMESTAMP, + Status = ''Success'' + WHERE LogID = $2', v_DestLogSchema); + EXECUTE v_SQL USING v_RecordsInserted, v_LogID; + + EXCEPTION WHEN OTHERS THEN + -- Rollback of the subtransaction happens automatically here. + -- Get the error message + GET STACKED DIAGNOSTICS v_ErrorMessage = MESSAGE_TEXT; + + -- Update log record on failure + v_SQL := format(' + UPDATE %I.ArchiveAuditLog + SET EndTime = CURRENT_TIMESTAMP, + Status = ''Error'', + ErrorMessage = $1 + WHERE LogID = $2', v_DestLogSchema); + EXECUTE v_SQL USING v_ErrorMessage, v_LogID; + + RAISE WARNING 'Error archiving table %: %', v_CurrentTable.table_name, v_ErrorMessage; + END; + END LOOP; +END; +$$; diff --git a/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-25.003-25.004.sql b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-25.003-25.004.sql new file mode 100644 index 000000000..f1946d7fb --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-25.003-25.004.sql @@ -0,0 +1,100 @@ +-- Create the conversion mapping table +CREATE TABLE onprc_ehr.RequirementName_Convert ( + searchid integer GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 1) NOT NULL, + PreviousDesignation varchar(255) NULL, + afterName varchar(255) NULL, + FileName varchar(1000) NULL, + CONSTRAINT PK_RequirementName_Convert PRIMARY KEY (searchid) -- TODO: Note - no PK on SQL Server +); + +/* +** +** Created by Date Comment +** +** +** Blasa 1/6/2026 Convert Compliance Requirement Names to its new predefined names. +*/ + +CREATE OR REPLACE FUNCTION onprc_ehr.sp_Compliance_requirementname_Update_Process() +RETURNS integer +LANGUAGE plpgsql +AS $$ +DECLARE + v_SearchKey integer := 0; + v_TempSearchKey integer := 0; + v_Code varchar(500); +BEGIN + -- Initial query to get the first searchid + SELECT searchid INTO v_SearchKey + FROM onprc_ehr.RequirementName_Convert + ORDER BY searchid + LIMIT 1; + + -- If no records exist, exit early with success + IF v_SearchKey IS NULL THEN + RETURN 0; + END IF; + + WHILE v_TempSearchKey < v_SearchKey LOOP + + -- Get the PreviousDesignation code for the current searchid + SELECT PreviousDesignation INTO v_Code + FROM onprc_ehr.RequirementName_Convert + WHERE searchid = v_SearchKey + LIMIT 1; + + -- 1. Process Requirement Names + UPDATE ehr_compliancedb.Requirements ss + SET RequirementName = TRIM(jj.aftername) || ' ' || TRIM(jj.filename) + FROM onprc_ehr.RequirementName_Convert jj + WHERE ss.RequirementName ILIKE TRIM(v_Code) || '%' + AND jj.PreviousDesignation ILIKE TRIM(v_Code) || '%'; + + -- 2. Process Completion Dates + UPDATE ehr_compliancedb.CompletionDates ss + SET RequirementName = TRIM(jj.aftername) || ' ' || TRIM(jj.filename) + FROM onprc_ehr.RequirementName_Convert jj + WHERE ss.RequirementName ILIKE TRIM(v_Code) || '%' + AND jj.PreviousDesignation ILIKE TRIM(v_Code) || '%'; + + -- 3. Process Requirements per Employees + UPDATE ehr_compliancedb.RequirementsPerEmployee ss + SET RequirementName = TRIM(jj.aftername) || ' ' || TRIM(jj.filename) + FROM onprc_ehr.RequirementName_Convert jj + WHERE ss.RequirementName ILIKE TRIM(v_Code) || '%' + AND jj.PreviousDesignation ILIKE TRIM(v_Code) || '%'; + + -- 4. Process Requirements per Categories + UPDATE ehr_compliancedb.RequirementsPerCategory ss + SET RequirementName = TRIM(jj.aftername) || ' ' || TRIM(jj.filename) + FROM onprc_ehr.RequirementName_Convert jj + WHERE ss.RequirementName ILIKE TRIM(v_Code) || '%' + AND jj.PreviousDesignation ILIKE TRIM(v_Code) || '%'; + + -- 5. Process Employee Requirements Exemptions + UPDATE ehr_compliancedb.EmployeeRequirementExemptions ss + SET RequirementName = TRIM(jj.aftername) || ' ' || TRIM(jj.filename) + FROM onprc_ehr.RequirementName_Convert jj + WHERE ss.RequirementName ILIKE TRIM(v_Code) || '%' + AND jj.PreviousDesignation ILIKE TRIM(v_Code) || '%'; + + -- Set temp key to current key to advance the cursor state + v_TempSearchKey := v_SearchKey; + + -- Fetch the next searchid + SELECT searchid INTO v_SearchKey + FROM onprc_ehr.RequirementName_Convert + WHERE searchid > v_TempSearchKey + ORDER BY searchid + LIMIT 1; + + -- If no more records are found, exit the loop + IF NOT FOUND OR v_SearchKey IS NULL THEN + EXIT; + END IF; + + END LOOP; + + RETURN 0; +END; +$$; diff --git a/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-25.004-25.005.sql b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-25.004-25.005.sql new file mode 100644 index 000000000..b925fb0cd --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-25.004-25.005.sql @@ -0,0 +1,100 @@ +-- TODO: I left TIMESTAMP(0) types here (that's how Gemini translated SmallDateTime), but I'm guessing we may want TIMESTAMP for consistency + +-- Create temporary report processing table +CREATE TABLE onprc_ehr.Rpt_TempJmacDate( + searchid integer GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 1) NOT NULL, + animalid varchar(200) NULL, + JBGRemovalDate timestamp(0) NULL, + JBGActualRemovalDate timestamp(0) NULL, + CONSTRAINT PK_Rpt_TempJmacDate PRIMARY KEY (searchid) -- TODO: Note - no PK on SQL Server +); + +-- Create permanent removal date table +CREATE TABLE onprc_ehr.JmacRemovalDate( + searchid integer GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 1) NOT NULL, + Id varchar(100) NULL, + JBGRemovalDate timestamp(0) NULL, + JBGActualRemovalDate timestamp(0) NULL, + DaysDiff double precision NULL, + reason varchar(100) NULL, + CONSTRAINT PK_JmacRemovalDate PRIMARY KEY (searchid) -- TODO: Note - no PK on SQL Server +); + +/* +** +** Created by Date Comment +** +** blasa 4/10/2026 Process to update jmac Removal date +** +** +** +**/ + +CREATE FUNCTION onprc_ehr.s_JmacRemovalDateProcess() +RETURNS integer +LANGUAGE plpgsql +AS $$ +DECLARE + v_TempSearchKey integer := 0; + v_SearchKey integer := 0; + v_AnimalID varchar(100); + v_OrgRemovalDate timestamp(0); + v_ActualRemovalDate timestamp(0); +BEGIN + -- Reset the temp table + DELETE FROM onprc_ehr.Rpt_TempJmacDate; + + -- Set initial processing + -- Column list is explicitly defined to prevent conflicts with the auto-generated identity key + INSERT INTO onprc_ehr.Rpt_TempJmacDate (animalid, JBGRemovalDate, JBGActualRemovalDate) + SELECT Id, JBGRemovalDate, JBGActualRemovalDate + FROM onprc_ehr.JmacRemovalDate + ORDER BY searchid; + + -- Get first searchid + SELECT searchid INTO v_SearchKey + FROM onprc_ehr.Rpt_TempJmacDate + ORDER BY searchid + LIMIT 1; + + -- If no records exist, exit early with success + IF v_SearchKey IS NULL THEN + RETURN 0; + END IF; + + WHILE v_TempSearchKey < v_SearchKey LOOP + v_AnimalID := ''; + v_OrgRemovalDate := NULL; + v_ActualRemovalDate := NULL; + + -- Fetch current record + SELECT animalid, JBGRemovalDate, JBGActualRemovalDate + INTO v_AnimalID, v_OrgRemovalDate, v_ActualRemovalDate + FROM onprc_ehr.Rpt_TempJmacDate + WHERE searchid = v_SearchKey; + + -- Begin updating target records + UPDATE studydataset.c6d346_animal_group_members + SET enddate = v_ActualRemovalDate + WHERE Participantid = v_AnimalID + AND enddate::date = v_OrgRemovalDate::date; + + -- Advance loop cursor + v_TempSearchKey := v_SearchKey; + + SELECT searchid INTO v_SearchKey + FROM onprc_ehr.Rpt_TempJmacDate + WHERE searchid > v_TempSearchKey + ORDER BY searchid + LIMIT 1; + + -- If no more records are found, exit the loop + IF NOT FOUND OR v_SearchKey IS NULL THEN + EXIT; + END IF; + + END LOOP; + + RETURN 0; +END; +$$; diff --git a/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-26.000-26.001.sql b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-26.000-26.001.sql new file mode 100644 index 000000000..8c3d4a87a --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-26.000-26.001.sql @@ -0,0 +1,274 @@ +-- TODO: I left TIMESTAMP(0) types here (that's how Gemini translated SmallDateTime), but I'm guessing we may want TIMESTAMP for consistency + +-- Cleanly drop existing tables and functions using standard PostgreSQL DDL +DROP TABLE IF EXISTS onprc_ehr.TB_TestTemp; +DROP TABLE IF EXISTS onprc_ehr.TB_TestTempMaster; +DROP TABLE IF EXISTS onprc_ehr.Temp_Clinical_Observations; +DROP TABLE IF EXISTS onprc_ehr.Temp_Clinical_Observations_Master; +DROP TABLE IF EXISTS onprc_ehr.Observation_EHRTasks; +DROP FUNCTION IF EXISTS onprc_ehr.p_Create_TB_Observationrecords(); + +-- Create TB_TestTemp table +CREATE TABLE onprc_ehr.TB_TestTemp ( + rowid integer GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 1) NOT NULL, + animalid varchar(200) NULL, + date timestamp NULL, + objectid ENTITYID NOT NULL, -- Maintained ENTITYID data type as requested + created timestamp NULL, + createdby integer NULL, + performedby varchar(200) NULL, + modifiedby integer NULL, + date_posted timestamp(0) NULL, + CONSTRAINT PK_TB_TestTemp PRIMARY KEY (rowid) -- TODO: Note - no PK on SQL Server +); + +-- Create Temp_Clinical_Observations table +CREATE TABLE onprc_ehr.Temp_Clinical_Observations ( + rowid integer GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 1) NOT NULL, + Id varchar(200) NULL, + date timestamp(0) NULL, + category varchar(500) NULL, + area varchar(500) NULL, + observation varchar(500) NULL, + createdby integer NULL, + performedby varchar(500) NULL, + taskid varchar(4000) NULL, + qcstate integer NULL, + modifiedby integer NULL, + CONSTRAINT PK_Temp_Clinical_Observations PRIMARY KEY (rowid) -- TODO: Note - no PK on SQL Server +); + +-- Create Temp_Clinical_Observations_Master table +CREATE TABLE onprc_ehr.Temp_Clinical_Observations_Master ( + rowid integer GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 1) NOT NULL, + searchid integer NULL, + Id varchar(200) NULL, + date timestamp(0) NULL, + category varchar(500) NULL, + area varchar(500) NULL, + observation varchar(500) NULL, + createdby integer NULL, + performedby varchar(500) NULL, + taskid varchar(4000) NULL, + qcstate smallint NULL, + modifiedby INT NULL, -- TODO: smalldatetime on SQL Server is clearly wrong, so switched to INT + Posted_date timestamp(0) NULL, + CONSTRAINT PK_Temp_Clinical_Observations_Master PRIMARY KEY (rowid) -- TODO: Note - no PK on SQL Server +); + +-- Create Observation_EHRTasks table +CREATE TABLE onprc_ehr.Observation_EHRTasks ( + rowid integer GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 1) NOT NULL, + taskid varchar(4000) NULL, + description varchar(500) NULL, + title varchar(500) NULL, + qcstate smallint NULL, + formtype varchar(500) NULL, + category varchar(500) NULL, + assignedto smallint NULL, + createdby smallint NULL, + modifiedby smallint NULL, + CONSTRAINT PK_Observation_EHRTasks PRIMARY KEY (rowid) -- TODO: Note - no PK on SQL Server +); + +/* +** +** Created by +** R. Blasa 6-24-2026 A Program Process that reviews all TB Test Encounter entries on a current date, and creates a +** new TB Test Clinical Observation record based on +** having the same monkey id, date, and then to be assigned to a Data Admin for reviews. +** +** Modified program so that each Clinical Observation entries generated by the program is assigned +** only a single task id when the program executes daily. +** +** +*/ + +CREATE OR REPLACE FUNCTION onprc_ehr.p_Create_TB_Observationrecords() +RETURNS integer +LANGUAGE plpgsql +AS $$ +DECLARE + v_SearchKey integer; + v_TempSearchKey integer; + v_TaskId varchar(4000); + v_AnimalID varchar(100); + v_date timestamp(0); + v_createdby integer; + v_performedby varchar(500); + v_modifiedby integer; + v_RunID varchar(4000); + v_FirstFlag integer; + v_TestDate timestamp(0); +BEGIN + -- Reset temp tables + TRUNCATE TABLE onprc_ehr.TB_TestTemp RESTART IDENTITY; + TRUNCATE TABLE onprc_ehr.Temp_Clinical_Observations RESTART IDENTITY; + TRUNCATE TABLE onprc_ehr.Observation_EHRTasks RESTART IDENTITY; + + -- Generate a list of TB test monkeys + INSERT INTO onprc_ehr.TB_TestTemp (animalid, date, objectid, created, createdby, performedby, modifiedby, date_posted) + SELECT + a.participantid, + a.date, + a.objectid, + a.created, + a.createdBy, + a.performedby, + a.modifiedby, + CURRENT_TIMESTAMP + FROM studydataset.c6d214_encounters a + WHERE lower(a.type) IN (lower('Procedure'), lower('Surgery')) + AND a.qcstate = 18 + AND a.procedureid = 802 + AND a.modified >= CURRENT_DATE + AND a.participantid IN ( + SELECT k.participantid + FROM studydataset.c6d203_demographics k + WHERE lower(k.calculated_status) = lower('Alive') + ) + AND a.participantid NOT IN ( + SELECT j.participantid + FROM studydataset.c6d171_clinical_observations j + WHERE j.participantid = a.participantid + AND j.date = a.date + INTERVAL '3 days' + AND lower(j.category) = lower('TB TST Score (72 hr)') + AND j.qcstate = 18 + ); + + -- Exit early if no records were found to process (replacing GOTO No_Records) + IF NOT EXISTS (SELECT 1 FROM onprc_ehr.TB_TestTemp) THEN + RETURN 0; + END IF; + + -- Reset temp variables + v_SearchKey := 0; + v_TempSearchKey := 0; + v_date := NULL; + v_modifiedby := NULL; + v_createdby := NULL; + v_performedby := NULL; + v_TaskId := NULL; + v_AnimalID := NULL; + v_RunID := NULL; + v_FirstFlag := 0; + + -- Extract initial rowid + SELECT rowid INTO v_SearchKey + FROM onprc_ehr.TB_TestTemp + ORDER BY rowid + LIMIT 1; + + -- Loop to create tasks and clinical observations + WHILE v_TempSearchKey < v_SearchKey LOOP + + SELECT animalid, date, modifiedby, createdby, performedby + INTO v_AnimalID, v_date, v_modifiedby, v_createdby, v_performedby + FROM onprc_ehr.TB_TestTemp + WHERE rowid = v_SearchKey; + + IF NOT EXISTS ( + SELECT 1 FROM studydataset.c6d171_clinical_observations j + WHERE j.participantid = v_AnimalID + AND j.date = v_date + INTERVAL '3 days' + AND lower(j.category) = lower('TB TST Score (72 hr)') + AND j.qcstate = 18 + ) THEN + + IF v_FirstFlag != 1 THEN + -- Create a new unique task ID + v_TaskId := gen_random_uuid()::text; + + -- Create Clinical Observation Task Entry + INSERT INTO onprc_ehr.Observation_EHRTasks ( + taskid, + description, + title, + qcstate, + formtype, + category, + assignedto, + createdby, + modifiedby + ) VALUES ( + v_TaskId, + 'TB TST Scores ' || COALESCE(v_date::text, ''), + 'TB TST Scores', + 20, + 'TB TST Scores', + 'task', + 1822, + 1042, + 1042 + ); + + v_FirstFlag := 1; + END IF; + + -- Initialize data entries (Add three days from TB Test date) + v_date := v_date + INTERVAL '3 days'; + + -- Create a Clinical Observation Record + INSERT INTO onprc_ehr.Temp_Clinical_Observations ( + Id, + date, + category, + area, + observation, + createdby, + performedby, + taskid, + qcstate, + modifiedby + ) VALUES ( + v_AnimalID, + v_date, + 'TB TST Score (72 hr)', + 'Right Eyelid', + 'Grade: Negative', + 1042, + v_performedby, + v_TaskId, + 20, + 1042 + ); + + END IF; + + -- Fetch the next record + v_TempSearchKey := v_SearchKey; + + SELECT rowid INTO v_SearchKey + FROM onprc_ehr.TB_TestTemp + WHERE rowid > v_TempSearchKey + ORDER BY rowid + LIMIT 1; + + IF NOT FOUND OR v_SearchKey IS NULL THEN + EXIT; + END IF; + + END LOOP; + + -- Create a master copy of the completed transaction + INSERT INTO onprc_ehr.Temp_Clinical_Observations_Master ( + searchid, Id, date, category, area, observation, createdby, performedby, taskid, qcstate, modifiedby, Posted_date + ) + SELECT + rowid, + Id, + date, + category, + area, + observation, + createdby, + performedby, + taskid, + qcstate, + modifiedby, + CURRENT_TIMESTAMP + FROM onprc_ehr.Temp_Clinical_Observations; + + RETURN 0; +END; +$$; diff --git a/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-26.001-26.002.sql b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-26.001-26.002.sql new file mode 100644 index 000000000..dad873777 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-26.001-26.002.sql @@ -0,0 +1,66 @@ +CREATE TABLE onprc_ehr.Rpt_TempProblemList ( + searchid integer GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 1) NOT NULL, + animalid varchar(200) NULL, + date timestamp NULL, + objectid varchar(4000) NULL, + caseid varchar(4000) NULL +); + +CREATE TABLE onprc_ehr.Rpt_TempProblemListMaster ( + searchid integer GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 1) NOT NULL, + animalid varchar(200) NULL, + date timestamp NULL, + objectid varchar(4000) NULL, + caseid varchar(4000) NULL +); + +/* +** +** Created by Date Comment +** +** blasa 7-7-2026 Process to update historical problem list records +** +** +** +*/ + +CREATE OR REPLACE FUNCTION onprc_ehr.s_MasterProblemHistoricalProcess() +RETURNS integer AS $$ +DECLARE + rec RECORD; +BEGIN + ----- Reset the temp table + DELETE FROM onprc_ehr.Rpt_TempProblemList; + + --- Set initial processing + INSERT INTO onprc_ehr.Rpt_TempProblemList (animalid, date, objectid, caseid) + SELECT participantid, + date, + objectid, + caseid + FROM studydataset.c6d200_problem + WHERE lower(category) = lower('Wound') + AND lower(subcategory) = lower('Digit Amputation') + AND qcstate = 18 + ORDER BY participantid; + + ------- Begin updating records + FOR rec IN + SELECT animalid, date, objectid + FROM onprc_ehr.Rpt_TempProblemList + ORDER BY searchid + LOOP + UPDATE studydataset.c6d200_problem pb + SET subcategory = 'Digit Removal/Caudectomy' + WHERE pb.Participantid = rec.animalid + AND pb.objectid = rec.objectid; + END LOOP; + + ---- Create an audit record of these entries + INSERT INTO onprc_ehr.Rpt_TempProblemListMaster (animalid, date, objectid, caseid) + SELECT animalid, date, objectid, caseid + FROM onprc_ehr.Rpt_TempProblemList; + + RETURN 0; +END; +$$ LANGUAGE plpgsql; diff --git a/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-26.002-26.003.sql b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-26.002-26.003.sql new file mode 100644 index 000000000..3580eee74 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/postgresql/onprc_ehr-26.002-26.003.sql @@ -0,0 +1,123 @@ +CREATE OR REPLACE FUNCTION audit.ArchiveAuditTables( + INOUT RetentionMonths INT +) +LANGUAGE plpgsql +AS $$ +DECLARE + v_DestSchema TEXT := 'labkey_audit'; -- Destination schema representing the destination database/namespace + v_SchemaName TEXT := 'audit'; + v_CutoffDate TIMESTAMP; + v_LogID INT; + v_CurrentTable TEXT; + v_ColumnList TEXT; + v_InsertCount INT; + v_ErrorMessage TEXT; +BEGIN + RetentionMonths := CASE + WHEN RetentionMonths - 6 > 12 THEN RetentionMonths - 6 + ELSE 12 + END; + + RAISE NOTICE 'Archiving audit logs older than % months old', RetentionMonths; + + v_CutoffDate := CURRENT_TIMESTAMP - (RetentionMonths || ' months')::INTERVAL; + + -- Validate source schema exists + IF NOT EXISTS (SELECT 1 FROM information_schema.schemata WHERE schema_name = v_SchemaName) THEN + RAISE EXCEPTION 'Source schema "%" does not exist', v_SchemaName; + END IF; + + -- Create destination schema if not exists + EXECUTE format('CREATE SCHEMA IF NOT EXISTS %I', v_DestSchema); + + -- Create ArchiveAuditLog table if not exists in destination schema + EXECUTE format(' + CREATE TABLE IF NOT EXISTS %I.ArchiveAuditLog ( + LogID INT GENERATED BY DEFAULT AS IDENTITY, + TableName VARCHAR(128) NOT NULL, + Operation VARCHAR(50) NOT NULL, + StartTime TIMESTAMP NOT NULL, + EndTime TIMESTAMP NULL, + Status VARCHAR(50) NULL, + RecordsProcessed INT NULL, + ErrorMessage TEXT NULL, + RetentionMonths INT NULL, + + CONSTRAINT PK_ArchiveAuditLog PRIMARY KEY (LogID) + )', v_DestSchema); + + -- Iterate over tables in source schema (excluding specified audit domains) + FOR v_CurrentTable IN + SELECT table_name + FROM information_schema.tables + WHERE table_schema = v_SchemaName + AND table_type = 'BASE TABLE' + AND table_name NOT IN ('c3d330_userauditdomain', 'c3d317_groupauditdomain') + LOOP + -- Log the start of archiving for current table + EXECUTE format(' + INSERT INTO %I.ArchiveAuditLog (TableName, Operation, StartTime, Status, RetentionMonths) + VALUES ($1, ''Archive'', clock_timestamp(), ''Started'', $2) + RETURNING LogID', v_DestSchema) + INTO v_LogID + USING v_CurrentTable, RetentionMonths; + + BEGIN + -- Create destination table if it does not exist (cloning structure from source table) + EXECUTE format( + 'CREATE TABLE IF NOT EXISTS %I.%I (LIKE %I.%I INCLUDING ALL)', + v_DestSchema, v_CurrentTable, v_SchemaName, v_CurrentTable + ); + + -- Build column list excluding identity columns and generated columns + SELECT string_agg(quote_ident(column_name), ', ') + INTO v_ColumnList + FROM information_schema.columns + WHERE table_schema = v_SchemaName + AND table_name = v_CurrentTable + AND is_identity = 'NO' + AND is_generated = 'NEVER'; + + -- Archive data: Insert records into destination and delete from source + EXECUTE format(' + WITH moved_rows AS ( + DELETE FROM %I.%I + WHERE Created < $1 + RETURNING %s + ) + INSERT INTO %I.%I (%s) + SELECT %s FROM moved_rows', + v_SchemaName, v_CurrentTable, + v_ColumnList, + v_DestSchema, v_CurrentTable, v_ColumnList, + v_ColumnList + ) + USING v_CutoffDate; + + GET DIAGNOSTICS v_InsertCount = ROW_COUNT; + + -- Update log with success status + EXECUTE format(' + UPDATE %I.ArchiveAuditLog + SET RecordsProcessed = $1, + EndTime = clock_timestamp(), + Status = ''Success'' + WHERE LogID = $2', v_DestSchema) + USING v_InsertCount, v_LogID; + + EXCEPTION WHEN OTHERS THEN + v_ErrorMessage := 'Error archiving ' || v_CurrentTable || ': ' || SQLERRM; + + EXECUTE format(' + UPDATE %I.ArchiveAuditLog + SET EndTime = clock_timestamp(), + Status = ''Error'', + ErrorMessage = $1 + WHERE LogID = $2', v_DestSchema) + USING v_ErrorMessage, v_LogID; + + RAISE WARNING '%', v_ErrorMessage; + END; + END LOOP; +END; +$$; 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 deleted file mode 100644 index 094bacee8..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-0.00-18.10.sql +++ /dev/null @@ -1,322 +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.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-0.000-25.000.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-0.000-25.000.sql new file mode 100644 index 000000000..9d5c0963d --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-0.000-25.000.sql @@ -0,0 +1,5734 @@ +/* + * 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... + +/* 18.xxx SQL scripts */ + +-- includes content of onprc_ehr-12.395-12.396.sql to onprc_ehr-17.704-17.705.sql from onprc19.1Prod +-- removing all references to eIACUC processing + + + +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 + +/* 20.xxx SQL scripts */ + +/* 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] + +/* 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 + +/* 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 + +/* 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 + +/* 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 + +/* 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 + +/****** 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 ******/ + +EXEC core.fn_dropifexists 'potentialDam_Source','onprc_ehr','TABLE'; +GO + +EXEC core.fn_dropifexists 'potentialsire_Source','onprc_ehr','TABLE'; +GO + +EXEC core.fn_dropifexists 'potentialParents_Source','onprc_ehr','TABLE'; +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) +) + +GO + +/****** 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 + +GO + +/****** 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 + +GO + +-- 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 + +/****** 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 + +GO + +EXEC core.fn_dropifexists 'StudyDetails_Reference_Data','onprc_ehr','TABLE'; +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 + +ALTER TABLE onprc_ehr.vet_assignment ADD project INT; + +/****** Housing transfers alert project: By Kolli******/ +/* + Created 3 temp tables to get the list of NHP rooms usage. + The stored proc manages the addition and deleting data from the temp tables + at the time of execution via ETL process. + */ +EXEC core.fn_dropifexists 'availableCages_temp','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'availableCagesByRoom_temp','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'roomUtilization_temp','onprc_ehr','TABLE'; + +GO + +-- Create the temp tables +CREATE TABLE [onprc_ehr].[availableCages_temp]( + [location] [varchar](50) NOT NULL, + [room] [varchar](200) NULL, + [cage] [varchar](200) NULL, + [row] [varchar](200) NULL, + [columnidx] [int] NULL, + [cage_type] [varchar](200) NULL, + [lowerCage] [varchar](200) NULL, + [lower_cage_type] [varchar](200) NULL, + [divider] [int] NULL, + [isAvailable] [int] NULL, + [isMarkedUnavailable] [int] NULL, + ) +; + +CREATE TABLE [onprc_ehr].[availableCagesByRoom_temp]( + [room] [varchar](200) NULL, + [availableCages] [int] NULL, + [markedUnavailable] [int] NULL + ) +; + +CREATE TABLE [onprc_ehr].[roomUtilization_temp]( + [room] [nvarchar](200) NULL, + [availableCages] [int] NULL, + [cagesUsed] [int] NULL, + [markedUnavailable] [int] NULL, + [cagesEmpty] [int] NULL, + [totalAnimals] [int] NULL + ) +; + +GO + + +-- Create the stored proc here +/****** Object: StoredProcedure [onprc_ehr].[NHPRoomsUsage] ******/ + +-- ============================================= +-- Author: Lakshmi Kolli +-- Create date: 3/6/2021 +-- Description: Get the list of NHP rooms usage. The procedure is scheduled using a ETL process +-- to list out the room utilization list at 4pm every day. The list is later used to check against for the +-- empty rooms with the current list of rooms usage. +-- ============================================= +CREATE PROCEDURE [onprc_ehr].[NHPRoomsUsage] + +AS +BEGIN + +----Truncate the temp table first +delete from onprc_ehr.availableCages_temp + +----Get the cages list and insert into the temp table +Insert Into onprc_ehr.availableCages_temp(location,room, cage, row, columnidx, cage_type, lowerCage, lower_cage_type, divider, isAvailable, isMarkedUnavailable) +SELECT + CASE + WHEN c.cage IS NULL THEN c.room + ELSE (c.room + '-' + c.cage) + END as location, + c.room, + c.cage, + (Select cp.row from ehr_lookups.cage_positions cp where c.cage = cp.cage) as row, + (Select cp.columnIdx from ehr_lookups.cage_positions cp where c.cage = cp.cage) as columnidx, + c.cage_type, + lc.cage as lowerCage, + lc.cage_type as lower_cage_type, + lc.divider, + --if the divider on the left-hand cage is separating, then these cages are separate + --and should be counted. if there's no left-hand cage, always include + CASE + WHEN c.cage_type = 'No Cage' THEN 0 + --WHEN lc.divider.countAsSeparate = 0 THEN false + WHEN (Select d.countAsSeparate from ehr_lookups.divider_types d where lc.divider = d.rowid) = 0 THEN 0 + ELSE 1 + END as isAvailable, + + CASE + WHEN (c.status IS NOT NULL AND c.status = 'Unavailable') then 1 + ELSE 0 + END as isMarkedUnavailable + +FROM ehr_lookups.cage c + --find the cage located to the left + LEFT JOIN ehr_lookups.cage lc ON (lc.cage_type != 'No Cage' and c.room = lc.room and (Select cp.row from ehr_lookups.cage_positions cp where c.cage = cp.cage) = (Select cp.row from ehr_lookups.cage_positions cp where lc.cage = cp.cage) and ((Select cp.columnIdx from ehr_lookups.cage_positions cp where c.cage = cp.cage) - 1) = (Select cp.columnIdx from ehr_lookups.cage_positions cp where lc.cage = cp.cage) ) +--WHERE c.room.housingType.value = 'Cage Location' + +----Truncate the temp table first +delete from onprc_ehr.availableCagesByRoom_temp + +--Get the available cages by room +Insert Into onprc_ehr.availableCagesByRoom_temp(room, availableCages, markedUnavailable) +SELECT + c.room, + count(*) as availableCages, + sum(c.isMarkedUnavailable) as markedUnavailable +FROM onprc_ehr.availableCages_temp c +WHERE c.isAvailable = 1 +GROUP BY c.room + +----Truncate the temp table first +delete from onprc_ehr.roomUtilization_temp + +--Get the rooms usage data +Insert Into onprc_ehr.roomUtilization_temp(room, availableCages, CagesUsed, MarkedUnavailable, CagesEmpty, TotalAnimals) +SELECT + r.room, + max(cbr.availableCages) as AvailableCages, + count(DISTINCT h.cage) as CagesUsed, + max(cbr.markedUnavailable) as MarkedUnavailable, + max(cbr.availableCages) - count(DISTINCT h.cage) - max(cbr.markedUnavailable) as CagesEmpty, + count(DISTINCT h.participantid) as TotalAnimals +FROM ehr_lookups.rooms r + LEFT JOIN ( + SELECT c.room, c.cage + FROM ehr_lookups.cage c + WHERE cage is not null + + --allow for rooms w/o cages + UNION ALL + SELECT r.room, null as cage + FROM ehr_lookups.rooms r + ) c on (r.room = c.room) + LEFT JOIN studyDataset.c6d194_housing h ON (r.room=h.room AND (c.cage=h.cage OR (c.cage is null and h.cage is null)) AND (((date <= GETDATE() AND enddate >= GETDATE()) OR (date <= GETDATE() AND enddate is null)))) + LEFT JOIN onprc_ehr.availableCagesByRoom_temp cbr ON (cbr.room = r.room) +WHERE r.datedisabled is null +GROUP BY r.room + +END + +GO + +EXEC core.fn_dropifexists 'PMIC_Reference_Data','onprc_ehr','TABLE'; + GO + +/****** Object: Table [onprc_ehr].[PMIC_Reference_Data] Script Date: 2/12/2020 ******/ +CREATE TABLE [onprc_ehr].[PMIC_Reference_Data]( + [RowId] INT IDENTITY(1,1)NOT NULL, + [value] [nvarchar](1000) NULL, + [name] [nvarchar](1000) NULL, + [remark] [nvarchar](4000) NULL, + [dateDisabled] [datetime] NULL, + [created] [datetime] NULL, + [createdBy] [int] NULL, + [modified] [datetime] NULL, + [modifiedBy] [int] NULL + + CONSTRAINT pk_PMIC_Reference_Data PRIMARY KEY (RowId) + ) + + GO + +ALTER TABLE onprc_ehr.AvailableBloodVolume ALTER COLUMN Id nvarchar(32) NOT NULL; +GO + +ALTER TABLE onprc_ehr.AvailableBloodVolume ADD CONSTRAINT PK_AvailableBloodVolume PRIMARY KEY (Id); +GO + +/* 21.xxx SQL scripts */ + +EXEC core.fn_dropifexists 'ASB_SpecialInstructions','onprc_ehr','TABLE'; +GO + +/****** Object: Table [onprc_ehr].[ASB_SpecialInstructions] Script Date: 6/8/21 ******/ +CREATE TABLE [onprc_ehr].[ASB_SpecialInstructions]( + [RowId] INT IDENTITY(1,1)NOT NULL, + [value] [nvarchar](1000) NOT NULL, + [remarks] [nvarchar](2000) NULL, + [dateDisabled] [datetime] NULL, + [created] [datetime] NULL, + [createdBy] [int] NULL, + [modified] [datetime] NULL, + [modifiedBy] [int] NULL + + CONSTRAINT pk_ASB_SpecialInstructions PRIMARY KEY (RowId) + ) + + GO + +EXEC core.fn_dropifexists 'ASB_SpecialInstructions','onprc_ehr','TABLE'; +GO + +/****** Object: Table [onprc_ehr].[ASB_SpecialInstructions] Script Date: 6/14/21 ******/ +CREATE TABLE [onprc_ehr].[ASB_SpecialInstructions]( + [value] [nvarchar](1000) NOT NULL, + [remarks] [nvarchar](2000) NULL, + [dateDisabled] [datetime] NULL, + [created] [datetime] NULL, + [createdBy] [int] NULL, + [modified] [datetime] NULL, + [modifiedBy] [int] NULL + + CONSTRAINT pk_ASB_SpecialInstructions PRIMARY KEY (value) + ) + + GO + +-- ======================================================================================================================================= +-- Author: Lakshmi Kolli +-- Create date: 2021-06-17 +-- Description: Db tables creation for Prima reporting process. Created all the Prima tables in Prime onprc_ehr schema folder. +-- ======================================================================================================================================= + +--Drop if exists (Labkey syntax) +--Tables +EXEC core.fn_dropifexists 'Prima_CaseBase','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_CassetteEvents','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_CassetteEventLocations','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_CassetteBases','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_LabstationTypes','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SlideBases','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SlideEvents','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SlideEventLocations','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_StainTests','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SurgicalWheels','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_UserPersons','onprc_ehr','TABLE'; +--Stored procs +EXEC core.fn_dropifexists 'PrimaSlideBillingReport', 'onprc_ehr', 'PROCEDURE'; +EXEC core.fn_dropifexists 'PrimaBlockBillingReport', 'onprc_ehr', 'PROCEDURE'; + +GO + +--Create tables +--1. UserPersons table +/****** Object: Table [onprc_ehr].[Prima_UserPersons] Script Date: 6/17/2021 3:52:21 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_UserPersons]( + [Id] [int] NOT NULL, + [DateOfBirth] [datetime] NULL, + [DepartmentName] [nvarchar](127) NULL, + [FirstName] [nvarchar](31) NULL, + [Gender] [tinyint] NOT NULL, + [LastName] [nvarchar](31) NULL, + [MiddleName] [nvarchar](31) NULL, + [Prefix] [int] NULL, + [SSN] [nvarchar](9) NULL, + [ProfessionalTitles] [nvarchar](127) NULL, + [DateOfDeath] [datetime] NULL + ) +; + +--2. SurgicalWheel table +/****** Object: Table [onprc_ehr].[Prima_SurgicalWheels] Script Date: 6/17/2021 3:53:24 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_SurgicalWheels]( + [Id] [int] IDENTITY(1,1) NOT NULL, + [Constant] [tinyint] NULL, + [Description] [nvarchar](255) NULL, + [IsActive] [bit] NOT NULL, + [CreatedByUserId] [int] NOT NULL, + [Deleted] [datetimeoffset](7) NULL, + [DeletedByUserId] [int] NULL, + [NextVersionId] [int] NULL, + [PreviousVersionId] [int] NULL, + [Title] [nvarchar](5) NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [LastModified] varchar(500) NOT NULL + ) +; + +--3. StainTests table +/****** Object: Table [onprc_ehr].[Prima_StainTests] Script Date: 6/17/2021 4:03:39 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_StainTests]( + [Id] [int] IDENTITY(1,1) NOT NULL, + [Abbreviation] [nvarchar](127) NOT NULL, + [Constant] [tinyint] NULL, + [CptCode] [nvarchar](6) NULL, + [Description] [nvarchar](255) NULL, + [StainTestCategoryId] [int] NOT NULL, + [TimeLength] [int] NOT NULL, + [CreatedByUserId] [int] NOT NULL, + [Deleted] [datetimeoffset](7) NULL, + [DeletedByUserId] [int] NULL, + [NextVersionId] [int] NULL, + [PreviousVersionId] [int] NULL, + [Title] [nvarchar](127) NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [LastModified] varchar(500) NOT NULL, + [IsValidated] [bit] NOT NULL + ) +; + +--4. Slidebases table +/****** Object: Table [onprc_ehr].[Prima_SlideBases] Script Date: 6/17/2021 4:04:46 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_SlideBases]( + [Id] [bigint] IDENTITY(1,1) NOT NULL, + [HandStain] [bit] NOT NULL, + [IsCharged] [bit] NOT NULL, + [StainTestId] [int] NOT NULL, + [DilutionFactor] [int] NULL, + [CaseBaseId] [int] NOT NULL, + [IsRadioActive] [bit] NOT NULL, + [PriorityLevelId] [int] NOT NULL, + [QcStatus] [tinyint] NOT NULL, + [SurgicalSerialPart] [smallint] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [OrderedStatus] [tinyint] NOT NULL, + [SavedIdentifier] [nvarchar](24) NULL, + [BarcodeContent] [nvarchar](72) NULL, + [CurrentBatchId] [int] NULL, + [AlternateIdentifier] [nvarchar](63) NULL, + [PrintStatus] [tinyint] NOT NULL, + [ItemStatus] [smallint] NOT NULL, + [FreeTextNotes] [nvarchar](4000) NULL + ) +; + +--5. CaseBase table +/****** Object: Table [onprc_ehr].[Prima_CaseBase] Script Date: 6/17/2021 4:07:39 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_CaseBase]( + [Id] [int] IDENTITY(1,1) NOT NULL, + [DifferentialDiagnosisId] [int] NULL, + [PathologistId] [int] NULL, + [PriorityLevelId] [int] NOT NULL, + [ResidentPathologistId] [int] NULL, + [SerialNumber] [int] NOT NULL, + [SurgeryDate] [datetime] NULL, + [SurgicalWheelId] [int] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [ResearcherId] [int] NULL, + [StudyId] [int] NULL, + [Discriminator] [nvarchar](128) NULL, + [StudyPhaseId] [int] NULL, + [CohortId] [int] NULL, + [SavedIdentifier] [nvarchar](max) NULL, + [Status] [tinyint] NOT NULL, + [AlternateIdentifier] [nvarchar](24) NULL + ) +; + +--6. CassetteEvents table +/****** Object: Table [onprc_ehr].[Prima_CassetteEvents] Script Date: 6/17/2021 4:08:57 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_CassetteEvents]( + [Id] [bigint] IDENTITY(1,1) NOT NULL, + [CassetteBaseId] [bigint] NOT NULL, + [EventType] [tinyint] NOT NULL, + [Status] [smallint] NOT NULL, + [Trigger] [tinyint] NOT NULL, + [UserId] [int] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [EventAction] [int] NULL, + [TissueProcessorId] [int] NULL, + [TissueProcessorProgramId] [int] NULL, + [Discriminator] [nvarchar](128) NOT NULL, + [CassetteBatchId] [int] NULL, + [CassetteOrderId] [bigint] NULL, + [AutomatedCassetteArchivalMachineId] [int] NULL, + [DisposalReasonId] [int] NULL, + [ShipmentId] [int] NULL, + [IsEstimated] [bit] NULL, + [PrintCount] [int] NULL, + [BarcodeContent] [nvarchar](max) NULL + ) +; + +--7. CassetteEventLocations table +/****** Object: Table [onprc_ehr].[Prima_CassetteEventLocations] Script Date: 6/17/2021 4:09:55 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_CassetteEventLocations]( + [CassetteEventId] [bigint] NOT NULL, + [LabStationTypeId] [int] NOT NULL, + [LocationId] [int] NOT NULL, + [WorkstationId] [int] NULL, + [Created] [datetimeoffset](7) NOT NULL, + [PersonId] [int] NULL + ) +; + +--8. CassetteBases table +/****** Object: Table [onprc_ehr].[Prima_CassetteBases] Script Date: 6/17/2021 4:10:42 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_CassetteBases]( + [Id] [bigint] IDENTITY(1,1) NOT NULL, + [CassetteColorId] [int] NOT NULL, + [EmbeddingInstructionId] [int] NOT NULL, + [EmbeddingNotes] [nvarchar](4000) NULL, + [HasTissue] [bit] NOT NULL, + [ProtocolCassetteId] [int] NULL, + [SpecimenBaseId] [bigint] NOT NULL, + [TissueCollectionId] [int] NULL, + [TissueProcessorProgramId] [int] NULL, + [TissueQuantity] [smallint] NOT NULL, + [CaseBaseId] [int] NOT NULL, + [IsRadioActive] [bit] NOT NULL, + [PriorityLevelId] [int] NOT NULL, + [QcStatus] [tinyint] NOT NULL, + [SurgicalSerialPart] [smallint] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [OrderedStatus] [tinyint] NOT NULL, + [SavedIdentifier] [nvarchar](24) NULL, + [BarcodeContent] [nvarchar](72) NULL, + [CurrentBatchId] [int] NULL, + [AlternateIdentifier] [nvarchar](63) NULL, + [PrintStatus] [tinyint] NOT NULL, + [ItemStatus] [smallint] NOT NULL + ) +; + +--9. LabstationTypes table +/****** Object: Table [onprc_ehr].[Prima_LabstationTypes] Script Date: 6/17/2021 4:41:00 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_LabstationTypes]( + [Id] [int] IDENTITY(1,1) NOT NULL, + [CanProcess] [int] NOT NULL, + [Constant] [int] NULL, + [Description] [nvarchar](255) NULL, + [IsEnabled] [bit] NOT NULL, + [Order] [int] NOT NULL, + [Title] [nvarchar](127) NULL, + [Created] [datetimeoffset](7) NOT NULL, + [LastModified] varchar(500) NOT NULL + ) +; + +--10. SlideEvents table +/****** Object: Table [onprc_ehr].[Prima_SlideEvents] Script Date: 6/17/2021 4:42:08 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_SlideEvents]( + [Id] [bigint] IDENTITY(1,1) NOT NULL, + [SlideBaseId] [bigint] NOT NULL, + [EventType] [tinyint] NOT NULL, + [Status] [smallint] NOT NULL, + [Trigger] [tinyint] NOT NULL, + [UserId] [int] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [EventAction] [int] NULL, + [CoverSlipperId] [int] NULL, + [OvenId] [int] NULL, + [OvenProgramId] [int] NULL, + [SlideImagerId] [int] NULL, + [SlideStainerId] [int] NULL, + [Discriminator] [nvarchar](128) NOT NULL, + [SlideBatchId] [int] NULL, + [SlideOrderId] [bigint] NULL, + [DisposalReasonId] [int] NULL, + [ShipmentId] [int] NULL, + [PrintCount] [int] NULL, + [BarcodeContent] [nvarchar](max) NULL, + [EquipmentId] [int] NULL, + [AutomatedSlideArchivalMachineId] [int] NULL + ) +; + +--11. SlideEventsLocations table +/****** Object: Table [onprc].[Prima_SlideEventLocations] Script Date: 6/17/2021 4:43:57 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_SlideEventLocations]( + [SlideEventId] [bigint] NOT NULL, + [LabStationTypeId] [int] NOT NULL, + [LocationId] [int] NOT NULL, + [WorkstationId] [int] NULL, + [Created] [datetimeoffset](7) NOT NULL, + [PersonId] [int] NULL + ) +; + +GO + +--Create the stored procedures for the SSRS reports +-- ======================================================================================================================================= +-- Author: Lakshmi Kolli +-- Create date: 2021-06-15 +-- Description: This stored procedure creates the Prima Slide billing report for the specified date range. +-- This proc is used to create the SSRS report. +-- ======================================================================================================================================= + +Create Procedure [onprc_ehr].[PrimaSlideBillingReport] + @startDate smalldatetime, + @endDate smalldatetime + +AS + +DECLARE +@staining int, +@embedding int, +@complete int + +BEGIN + --SET @startDate = '2000-01-01' -- 00:00:00.0000000 -07:00' + --SET @endDate = '2021-05-31' -- 00:00:00.0000000 -07:00' +SET @staining = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 10) +SET @embedding = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 7) +SET @complete = 7 SELECT Prima_surgicalwheels.title AS 'Surgical Wheel', + CASE + WHEN Prima_userpersons.lastname IS NOT NULL THEN + Concat(Prima_userpersons.lastname, ', ', Prima_userpersons.firstname, ' ', + Prima_userpersons.middlename) + ELSE 'Unassigned Pathologist' +END AS 'Pathologist', + Prima_staintests.title AS 'Stain Test', + sub2.slidecount AS 'Slide Count' + FROM (SELECT surgicalwheelid, + Prima_slidebases.staintestid, + Prima_casebase.pathologistid, + Count(*) AS SlideCount + FROM (SELECT Min(Prima_slideevents.created) AS VerifyOrBarcodeEventTime, + slidebaseid + FROM Prima_slideevents JOIN Prima_SlideEventLocations + ON Prima_slideeventlocations.SlideEventId = Prima_slideevents.id + AND Prima_slideeventlocations.LabStationTypeId = @staining WHERE eventtype = @complete + GROUP BY slidebaseid) sub + JOIN Prima_slidebases + ON slidebaseid = Prima_slidebases.id + JOIN Prima_casebase + ON Prima_casebase.id = Prima_slidebases.casebaseid WHERE sub.verifyorbarcodeeventtime >= @startDate + AND sub.verifyorbarcodeeventtime < @endDate + GROUP BY surgicalwheelid, + pathologistid, + staintestid) sub2 + LEFT JOIN Prima_userpersons + ON Prima_userpersons.id = sub2.pathologistid + LEFT JOIN Prima_surgicalwheels + ON Prima_surgicalwheels.id = sub2.surgicalwheelid + LEFT JOIN Prima_staintests + ON Prima_staintests.id = sub2.staintestid + ORDER BY 'Surgical Wheel', + 'Pathologist', + 'Stain Test' +END + +GO + +-- ======================================================================================================================================= +-- Author: Lakshmi Kolli +-- Create date: 2021-06-15 +-- Description: This stored procedure creates the Prima Block billing report for the specified date range. +-- This proc is used to create the SSRS report. +-- ======================================================================================================================================= + +CREATE Procedure [onprc_ehr].[PrimaBlockBillingReport] + @startDate smalldatetime, + @endDate smalldatetime + +AS + +DECLARE +@staining int, +@embedding int, +@complete int + +BEGIN + --SET @startDate = '2000-01-01' -- 00:00:00.0000000 -07:00' + --SET @endDate = '2021-05-31' -- 00:00:00.0000000 -07:00' +SET @staining = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 10) +SET @embedding = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 7) +SET @complete = 7 + +SELECT Prima_surgicalwheels.title AS 'Surgical Wheel', + CASE + WHEN Prima_userpersons.lastname IS NOT NULL THEN + Concat(Prima_userpersons.lastname, ', ', Prima_userpersons.firstname, ' ', + Prima_userpersons.middlename) + ELSE 'Unassigned Pathologist' + END AS 'Pathologist', + sub2.cassettecount AS 'Cassette Count' +FROM (SELECT surgicalwheelid, + Prima_casebase.pathologistid, + Count(*) AS CassetteCount + FROM (SELECT Min(Prima_cassetteevents.created) AS VerifyOrBarcodeEventTime, + cassettebaseid + FROM Prima_cassetteevents + JOIN Prima_CassetteEventLocations + ON Prima_CassetteEventLocations.CassetteEventId = Prima_cassetteevents.id + AND Prima_CassetteEventLocations.LabStationTypeId = @embedding WHERE eventtype = @complete + GROUP BY cassettebaseid) sub + JOIN Prima_cassettebases + ON cassettebaseid = Prima_cassettebases.id + JOIN Prima_casebase + ON Prima_casebase.id = Prima_cassettebases.casebaseid + WHERE sub.verifyorbarcodeeventtime >= @startDate + AND sub.verifyorbarcodeeventtime < @endDate + GROUP BY surgicalwheelid, + pathologistid) sub2 + LEFT JOIN Prima_userpersons + ON Prima_userpersons.id = sub2.pathologistid + LEFT JOIN Prima_surgicalwheels + ON Prima_surgicalwheels.id = sub2.surgicalwheelid + ORDER BY 'Surgical Wheel', + 'Pathologist' +END + +GO + +-- ======================================================================================================================================= +-- Author: Lakshmi Kolli +-- Create date: 2021-06-17 +-- Description: Db tables creation for Prima reporting process. Created all the Prima tables in Prime onprc_ehr schema folder. +-- ======================================================================================================================================= + +--Drop if exists (Labkey syntax) +--Tables +EXEC core.fn_dropifexists 'Prima_CaseBase','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_CassetteEvents','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_CassetteEventLocations','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_CassetteBases','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_LabstationTypes','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SlideBases','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SlideEvents','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SlideEventLocations','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_StainTests','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SurgicalWheels','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_UserPersons','onprc_ehr','TABLE'; +--Stored procs +EXEC core.fn_dropifexists 'PrimaSlideBillingReport', 'onprc_ehr', 'PROCEDURE'; +EXEC core.fn_dropifexists 'PrimaBlockBillingReport', 'onprc_ehr', 'PROCEDURE'; + +GO + +--Create tables +--1. UserPersons table +/****** Object: Table [onprc_ehr].[Prima_UserPersons] Script Date: 6/17/2021 3:52:21 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_UserPersons]( + [Id] [int] NOT NULL, + [DateOfBirth] [datetime] NULL, + [DepartmentName] [nvarchar](127) NULL, + [FirstName] [nvarchar](31) NULL, + [Gender] [tinyint] NOT NULL, + [LastName] [nvarchar](31) NULL, + [MiddleName] [nvarchar](31) NULL, + [Prefix] [int] NULL, + [SSN] [nvarchar](9) NULL, + [ProfessionalTitles] [nvarchar](127) NULL, + [DateOfDeath] [datetime] NULL + ) +; + +--2. SurgicalWheel table +/****** Object: Table [onprc_ehr].[Prima_SurgicalWheels] Script Date: 6/17/2021 3:53:24 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_SurgicalWheels]( + [Id] [int] IDENTITY(1,1) NOT NULL, + [Constant] [tinyint] NULL, + [Description] [nvarchar](255) NULL, + [IsActive] [bit] NOT NULL, + [CreatedByUserId] [int] NOT NULL, + [Deleted] [datetimeoffset](7) NULL, + [DeletedByUserId] [int] NULL, + [NextVersionId] [int] NULL, + [PreviousVersionId] [int] NULL, + [Title] [nvarchar](5) NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [LastModified] [timestamp] NOT NULL + ) +; + +--3. StainTests table +/****** Object: Table [onprc_ehr].[Prima_StainTests] Script Date: 6/17/2021 4:03:39 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_StainTests]( + [Id] [int] IDENTITY(1,1) NOT NULL, + [Abbreviation] [nvarchar](127) NOT NULL, + [Constant] [tinyint] NULL, + [CptCode] [nvarchar](6) NULL, + [Description] [nvarchar](255) NULL, + [StainTestCategoryId] [int] NOT NULL, + [TimeLength] [int] NOT NULL, + [CreatedByUserId] [int] NOT NULL, + [Deleted] [datetimeoffset](7) NULL, + [DeletedByUserId] [int] NULL, + [NextVersionId] [int] NULL, + [PreviousVersionId] [int] NULL, + [Title] [nvarchar](127) NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [LastModified] [timestamp] NOT NULL, + [IsValidated] [bit] NOT NULL + ) +; + +--4. Slidebases table +/****** Object: Table [onprc_ehr].[Prima_SlideBases] Script Date: 6/17/2021 4:04:46 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_SlideBases]( + [Id] [bigint] IDENTITY(1,1) NOT NULL, + [HandStain] [bit] NOT NULL, + [IsCharged] [bit] NOT NULL, + [StainTestId] [int] NOT NULL, + [DilutionFactor] [int] NULL, + [CaseBaseId] [int] NOT NULL, + [IsRadioActive] [bit] NOT NULL, + [PriorityLevelId] [int] NOT NULL, + [QcStatus] [tinyint] NOT NULL, + [SurgicalSerialPart] [smallint] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [OrderedStatus] [tinyint] NOT NULL, + [SavedIdentifier] [nvarchar](24) NULL, + [BarcodeContent] [nvarchar](72) NULL, + [CurrentBatchId] [int] NULL, + [AlternateIdentifier] [nvarchar](63) NULL, + [PrintStatus] [tinyint] NOT NULL, + [ItemStatus] [smallint] NOT NULL, + [FreeTextNotes] [nvarchar](4000) NULL + ) +; + +--5. CaseBase table +/****** Object: Table [onprc_ehr].[Prima_CaseBase] Script Date: 6/17/2021 4:07:39 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_CaseBase]( + [Id] [int] IDENTITY(1,1) NOT NULL, + [DifferentialDiagnosisId] [int] NULL, + [PathologistId] [int] NULL, + [PriorityLevelId] [int] NOT NULL, + [ResidentPathologistId] [int] NULL, + [SerialNumber] [int] NOT NULL, + [SurgeryDate] [datetime] NULL, + [SurgicalWheelId] [int] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [ResearcherId] [int] NULL, + [StudyId] [int] NULL, + [Discriminator] [nvarchar](128) NULL, + [StudyPhaseId] [int] NULL, + [CohortId] [int] NULL, + [SavedIdentifier] [nvarchar](max) NULL, + [Status] [tinyint] NOT NULL, + [AlternateIdentifier] [nvarchar](24) NULL + ) +; + +--6. CassetteEvents table +/****** Object: Table [onprc_ehr].[Prima_CassetteEvents] Script Date: 6/17/2021 4:08:57 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_CassetteEvents]( + [Id] [bigint] IDENTITY(1,1) NOT NULL, + [CassetteBaseId] [bigint] NOT NULL, + [EventType] [tinyint] NOT NULL, + [Status] [smallint] NOT NULL, + [Trigger] [tinyint] NOT NULL, + [UserId] [int] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [EventAction] [int] NULL, + [TissueProcessorId] [int] NULL, + [TissueProcessorProgramId] [int] NULL, + [Discriminator] [nvarchar](128) NOT NULL, + [CassetteBatchId] [int] NULL, + [CassetteOrderId] [bigint] NULL, + [AutomatedCassetteArchivalMachineId] [int] NULL, + [DisposalReasonId] [int] NULL, + [ShipmentId] [int] NULL, + [IsEstimated] [bit] NULL, + [PrintCount] [int] NULL, + [BarcodeContent] [nvarchar](max) NULL + ) +; + +--7. CassetteEventLocations table +/****** Object: Table [onprc_ehr].[Prima_CassetteEventLocations] Script Date: 6/17/2021 4:09:55 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_CassetteEventLocations]( + [CassetteEventId] [bigint] NOT NULL, + [LabStationTypeId] [int] NOT NULL, + [LocationId] [int] NOT NULL, + [WorkstationId] [int] NULL, + [Created] [datetimeoffset](7) NOT NULL, + [PersonId] [int] NULL + ) +; + +--8. CassetteBases table +/****** Object: Table [onprc_ehr].[Prima_CassetteBases] Script Date: 6/17/2021 4:10:42 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_CassetteBases]( + [Id] [bigint] IDENTITY(1,1) NOT NULL, + [CassetteColorId] [int] NOT NULL, + [EmbeddingInstructionId] [int] NOT NULL, + [EmbeddingNotes] [nvarchar](4000) NULL, + [HasTissue] [bit] NOT NULL, + [ProtocolCassetteId] [int] NULL, + [SpecimenBaseId] [bigint] NOT NULL, + [TissueCollectionId] [int] NULL, + [TissueProcessorProgramId] [int] NULL, + [TissueQuantity] [smallint] NOT NULL, + [CaseBaseId] [int] NOT NULL, + [IsRadioActive] [bit] NOT NULL, + [PriorityLevelId] [int] NOT NULL, + [QcStatus] [tinyint] NOT NULL, + [SurgicalSerialPart] [smallint] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [OrderedStatus] [tinyint] NOT NULL, + [SavedIdentifier] [nvarchar](24) NULL, + [BarcodeContent] [nvarchar](72) NULL, + [CurrentBatchId] [int] NULL, + [AlternateIdentifier] [nvarchar](63) NULL, + [PrintStatus] [tinyint] NOT NULL, + [ItemStatus] [smallint] NOT NULL + ) +; + +--9. LabstationTypes table +/****** Object: Table [onprc_ehr].[Prima_LabstationTypes] Script Date: 6/17/2021 4:41:00 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_LabstationTypes]( + [Id] [int] IDENTITY(1,1) NOT NULL, + [CanProcess] [int] NOT NULL, + [Constant] [int] NULL, + [Description] [nvarchar](255) NULL, + [IsEnabled] [bit] NOT NULL, + [Order] [int] NOT NULL, + [Title] [nvarchar](127) NULL, + [Created] [datetimeoffset](7) NOT NULL, + [LastModified] [timestamp] NOT NULL + ) +; + +--10. SlideEvents table +/****** Object: Table [onprc_ehr].[Prima_SlideEvents] Script Date: 6/17/2021 4:42:08 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_SlideEvents]( + [Id] [bigint] IDENTITY(1,1) NOT NULL, + [SlideBaseId] [bigint] NOT NULL, + [EventType] [tinyint] NOT NULL, + [Status] [smallint] NOT NULL, + [Trigger] [tinyint] NOT NULL, + [UserId] [int] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [EventAction] [int] NULL, + [CoverSlipperId] [int] NULL, + [OvenId] [int] NULL, + [OvenProgramId] [int] NULL, + [SlideImagerId] [int] NULL, + [SlideStainerId] [int] NULL, + [Discriminator] [nvarchar](128) NOT NULL, + [SlideBatchId] [int] NULL, + [SlideOrderId] [bigint] NULL, + [DisposalReasonId] [int] NULL, + [ShipmentId] [int] NULL, + [PrintCount] [int] NULL, + [BarcodeContent] [nvarchar](max) NULL, + [EquipmentId] [int] NULL, + [AutomatedSlideArchivalMachineId] [int] NULL + ) +; + +--11. SlideEventsLocations table +/****** Object: Table [onprc].[Prima_SlideEventLocations] Script Date: 6/17/2021 4:43:57 PM ******/ +CREATE TABLE [onprc_ehr].[Prima_SlideEventLocations]( + [SlideEventId] [bigint] NOT NULL, + [LabStationTypeId] [int] NOT NULL, + [LocationId] [int] NOT NULL, + [WorkstationId] [int] NULL, + [Created] [datetimeoffset](7) NOT NULL, + [PersonId] [int] NULL + ) +; + +GO + +--Create the stored procedures for the SSRS reports +-- ======================================================================================================================================= +-- Author: Lakshmi Kolli +-- Create date: 2021-06-15 +-- Description: This stored procedure creates the Prima Slide billing report for the specified date range. +-- This proc is used to create the SSRS report. +-- ======================================================================================================================================= + +Create Procedure [onprc_ehr].[PrimaSlideBillingReport] + @startDate smalldatetime, + @endDate smalldatetime + +AS + +DECLARE +@staining int, +@embedding int, +@complete int + +BEGIN + --SET @startDate = '2000-01-01' -- 00:00:00.0000000 -07:00' + --SET @endDate = '2021-05-31' -- 00:00:00.0000000 -07:00' +SET @staining = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 10) +SET @embedding = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 7) +SET @complete = 7 SELECT Prima_surgicalwheels.title AS 'Surgical Wheel', + CASE + WHEN Prima_userpersons.lastname IS NOT NULL THEN + Concat(Prima_userpersons.lastname, ', ', Prima_userpersons.firstname, ' ', + Prima_userpersons.middlename) + ELSE 'Unassigned Pathologist' +END AS 'Pathologist', + Prima_staintests.title AS 'Stain Test', + sub2.slidecount AS 'Slide Count' + FROM (SELECT surgicalwheelid, + Prima_slidebases.staintestid, + Prima_casebase.pathologistid, + Count(*) AS SlideCount + FROM (SELECT Min(Prima_slideevents.created) AS VerifyOrBarcodeEventTime, + slidebaseid + FROM Prima_slideevents JOIN Prima_SlideEventLocations + ON Prima_slideeventlocations.SlideEventId = Prima_slideevents.id + AND Prima_slideeventlocations.LabStationTypeId = @staining WHERE eventtype = @complete + GROUP BY slidebaseid) sub + JOIN Prima_slidebases + ON slidebaseid = Prima_slidebases.id + JOIN Prima_casebase + ON Prima_casebase.id = Prima_slidebases.casebaseid WHERE sub.verifyorbarcodeeventtime >= @startDate + AND sub.verifyorbarcodeeventtime < @endDate + GROUP BY surgicalwheelid, + pathologistid, + staintestid) sub2 + LEFT JOIN Prima_userpersons + ON Prima_userpersons.id = sub2.pathologistid + LEFT JOIN Prima_surgicalwheels + ON Prima_surgicalwheels.id = sub2.surgicalwheelid + LEFT JOIN Prima_staintests + ON Prima_staintests.id = sub2.staintestid + ORDER BY 'Surgical Wheel', + 'Pathologist', + 'Stain Test' +END + + GO + +-- ======================================================================================================================================= +-- Author: Lakshmi Kolli +-- Create date: 2021-06-15 +-- Description: This stored procedure creates the Prima Block billing report for the specified date range. +-- This proc is used to create the SSRS report. +-- ======================================================================================================================================= + +CREATE Procedure [onprc_ehr].[PrimaBlockBillingReport] + @startDate smalldatetime, + @endDate smalldatetime + +AS + +DECLARE +@staining int, +@embedding int, +@complete int + +BEGIN + --SET @startDate = '2000-01-01' -- 00:00:00.0000000 -07:00' + --SET @endDate = '2021-05-31' -- 00:00:00.0000000 -07:00' +SET @staining = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 10) +SET @embedding = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 7) +SET @complete = 7 + +SELECT Prima_surgicalwheels.title AS 'Surgical Wheel', + CASE + WHEN Prima_userpersons.lastname IS NOT NULL THEN + Concat(Prima_userpersons.lastname, ', ', Prima_userpersons.firstname, ' ', + Prima_userpersons.middlename) + ELSE 'Unassigned Pathologist' + END AS 'Pathologist', + sub2.cassettecount AS 'Cassette Count' +FROM (SELECT surgicalwheelid, + Prima_casebase.pathologistid, + Count(*) AS CassetteCount + FROM (SELECT Min(Prima_cassetteevents.created) AS VerifyOrBarcodeEventTime, + cassettebaseid + FROM Prima_cassetteevents + JOIN Prima_CassetteEventLocations + ON Prima_CassetteEventLocations.CassetteEventId = Prima_cassetteevents.id + AND Prima_CassetteEventLocations.LabStationTypeId = @embedding WHERE eventtype = @complete + GROUP BY cassettebaseid) sub + JOIN Prima_cassettebases + ON cassettebaseid = Prima_cassettebases.id + JOIN Prima_casebase + ON Prima_casebase.id = Prima_cassettebases.casebaseid + WHERE sub.verifyorbarcodeeventtime >= @startDate + AND sub.verifyorbarcodeeventtime < @endDate + GROUP BY surgicalwheelid, + pathologistid) sub2 + LEFT JOIN Prima_userpersons + ON Prima_userpersons.id = sub2.pathologistid + LEFT JOIN Prima_surgicalwheels + ON Prima_surgicalwheels.id = sub2.surgicalwheelid +ORDER BY 'Surgical Wheel', + 'Pathologist' +END + + GO + +EXEC core.fn_dropifexists 'ASB_SpecialInstructions','onprc_ehr','TABLE'; +GO + +/****** Object: Table [onprc_ehr].[ASB_SpecialInstructions] Script Date: 6/14/21 ******/ +CREATE TABLE [onprc_ehr].[ASB_SpecialInstructions]( + [value] [nvarchar](1000) NOT NULL, + [remarks] [nvarchar](2000) NULL, + [dateDisabled] [datetime] NULL, + [created] [datetime] NULL, + [createdBy] [int] NULL, + [modified] [datetime] NULL, + [modifiedBy] [int] NULL + + CONSTRAINT pk_ASB_SpecialInstructions PRIMARY KEY (value) + ) + + GO + +EXEC core.fn_dropifexists 'StudyDetails_RandalData','onprc_ehr','TABLE'; +GO + +/****** Object: Table [onprc_ehr].[StudyDetails_RandalData] Script Date: 10/13/2021 +Purpose Target for import from external datasource mfsh +******/ + +CREATE TABLE [onprc_ehr].[StudyDetails_RandalData]( + [id] INT NOT NULL, + [Rh] [nvarchar](100) NULL, + [Cohort] [nvarchar](1000) NULL, + [PI] [nvarchar](100) NULL, + [Cohort_id] INT NULL, + [subcohort] [nvarchar](100) NULL, + [grp] [nvarchar](100) NULL, + [grp_order] INT NULL, + [grp_id] INT NOT NULL, + [rhCode] [nvarchar](100) NULL, + [grpnm] INT NULL, + [Sex] [nvarchar](100) NULL, + [cohortStart] [date] null, + [cohortEnd] [date] null, + [Do] [date] null, + [DPC0] [date] null, + [contprog] [nvarchar](100) NULl, + [PIDO] date null, + [DPTO] date Null, + [Birth] date null, + [Nx_date] date null, + [stims] [nvarchar](100) NULl, + [active] [nvarchar](100) NULl + CONSTRAINT pk_StudyDetails_Randal PRIMARY KEY (Id) + ) + + + + + + GO + +EXEC core.fn_dropifexists 'BSUageclass','onprc_ehr','TABLE'; +GO + + +CREATE TABLE [onprc_ehr].[BSUageclass] +( + [rowId] INT IDENTITY(1,1)NOT NULL, + label varchar(255) NULL, + species varchar(255) NULL, + gender varchar(5) NULL, + ageclass INT NULL, + min [float] NULL, + max [float] NULL, + [sort_order] INT NULL, + [dateDisabled] [datetime] NULL, + + CONSTRAINT PK_bsuageclass PRIMARY KEY (rowId) + + ) + GO + +/* 22.xxx SQL scripts */ + +-- This stored procedure was incorrectly named and placed in the wrong schema when created in onprc_ehr-18.10-20.101.sql. +-- It's also unused, so just drop it. +IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND object_id = OBJECT_ID('[dbo].[onprc_ehr.etlStep1eIACUCtoPRIMEProcessing]')) + DROP PROCEDURE [dbo].[onprc_ehr.etlStep1eIACUCtoPRIMEProcessing] + +--added to allow department descignation for R & L +EXEC core.fn_dropifexists 'Investigators', 'onprc_ehr', 'COLUMN', 'Department'; +GO +ALTER TABLE onprc_ehr.investigators ADD [Department] varchar(250) Null; + +/* 23.xxx SQL scripts */ + +CREATE TABLE [onprc_ehr].[Epoc_tests] +( + rowid INT IDENTITY(1,1)NOT NULL, + testid nvarchar(500) NOT NULL, + name nvarchar(500) NULL, + units nvarchar(50) NULL, + alias nvarchar(200) NULL, + alertOnAbnormal [bit] NULL, + alertOnAny [bit] NULL, + includeInPanel [bit]NULL, + objectid ENTITYID NOT NULL, + sort_order [int] NULL, + container ENTITYID + + CONSTRAINT PK_EpocTestsObject PRIMARY KEY (objectid) + + ) + GO + +CREATE TABLE onprc_ehr.Reference_Data_IDkey +( + rowId int identity(1,1), + displayName varchar(4000) DEFAULT NULL, + idkey integer NOT NULL, + columnName varchar(1000) NOT NULL, + status integer NULL, + type varchar(500) NULL, + sort_order integer null, + created datetime NOT NULL, + endDate datetime DEFAULT NULL + + + CONSTRAINT pk_referenceIDkey PRIMARY KEY (idkey) +) + + +GO + + +-- Author: R. Blasa +-- Created: 10-10-2022 +-- Description: Stored procedure program to initially populate onprc_ehr.Reference_Data_IDkey. + + +Create Procedure [onprc_ehr].[p_PopulateReferenceDataIDkey] + + +AS + + +BEGIN + ---- Reset lookiup table + + truncate table onprc_ehr.Reference_Data_IDkey + + ----- Create initial entries + Insert into onprc_ehr.Reference_Data_IDkey + select + + Name, + UserId, + 'Active_Groups', + Active, + Type, + NULL as sort_order, ---- Sort_Order + GETDATE() as created, ----- Created + NULL as enddate ----- Date Disabled + + FROM core.Principals + where type = 'g' + and UserId > 0 + and Active = 1 + and Container is null + + If @@Error <> 0 + GoTo Err_Proc + + + Return 0 + +Err_Proc: Return 1 + +END + +GO + +-- Created: 10-10-2022 R. Blasa to correct type definitionss + + +ALTER TABLE onprc_ehr.encounter_summaries_remarks ALTER COLUMN createdby userid; +GO + + +ALTER TABLE onprc_ehr.encounter_summaries_remarks ALTER COLUMN modifiedby userid; +GO + +CREATE TABLE [onprc_ehr].[PrimeProblemListTemp]( + [rowid] [int] IDENTITY(100,1) NOT NULL, + [animalid] [varchar](200) NULL, + [date] datetime NULL, + [objectid] [varchar](4000) NULL, + [caseid] [varchar](4000) NULL, + [case_enddate] datetime, + [created] datetime + + + ) + GO + + + +-- Author: R. Blasa +-- Created: 10-20-2022 +-- Description: Stored procedure program assigns Clinical Cases ending dates to all Clinical Problem list that +-- have no ending dates, and shares the same case ids + + +CREATE Procedure [onprc_ehr].[p_CaseToPRoblemListupdates] + + + + +AS + + + +DECLARE + @SearchKey Int, + @TempsearchKey Int, + @TempObjectID varchar(4000), + @TaskId varchar(4000), + @ObjectId varchar(4000), + @CaseEnddate datetime, + @SessionID Int + + + + +BEGIN + + + + ---- Reset temp table + +Truncate table onprc_ehr.PrimeProblemListTemp + + + If @@Error <> 0 + GoTo Err_Proc + + + + --- Generate a list of Problem List records to close ) + + Insert into onprc_ehr.PrimeProblemListTemp + + select + b.participantid, + b.date, + b.objectid, + b.caseid, + a.enddate ,------ case ending date + getdate() ------ date created + + + from studyDataset.c6d176_cases a, studyDataset.c6d200_problem b + where a.objectid = b.caseid + and a.category in ('clinical','Behavior') + and a.qcstate = 18 and b.qcstate = 18 + and b.enddate is null + and a.enddate is not null + and a.participantid = b.participantid + order by a.date desc + + + If @@Error <> 0 + GoTo Err_Proc + + + ---- Reset temp variables + +Set @SearchKey = 0 +Set @TempSearchKey = 0 +Set @TempObjectid = NULL +Set @CaseEnddate = NULL + +----- extract initial row id + +Select Top 1 @Searchkey = rowid from onprc_ehr.PrimeProblemListTemp +Order by rowid + + + While @TempSearchKey < @SearchKey + BEGIN + + -----Begin update process + + If exists (select * from onprc_ehr.PrimeProblemListTemp Where rowid = @SearchKey) + BEGIN + + Select @TempObjectid =objectid, @CaseEnddate = case_enddate from onprc_ehr.PrimeProblemListTemp + Where rowid = @Searchkey + + -------Begin record editing process + + Update prob + set prob.enddate = @CaseEnddate + From studyDataset.c6d200_problem prob + where prob.objectid = @TempObjectID + + + If @@Error <> 0 + GoTo Err_Proc + END + + + ----- Proceed and fetch the next record + + Set @TempSearchKey = @SearchKey + + Select Top 1 @SearchKey = rowid from onprc_ehr.PrimeProblemListTemp + Where rowid > @TempSearchKey + Order by rowid + + + END ---- While @TempSearchKey + + + ----- Create a master copy of the completed transaction + + Select * into onprc_ehr.PrimeProblemListMaster + from onprc_ehr.PrimeProblemListTemp + If @@Error <> 0 + GoTo Err_Proc + + + +No_Records: + + RETURN 0 + + +Err_Proc: + -------Error Generated, Transfer process stopped + RETURN 1 + + +END + +GO + +---Create 5-2023-08-15 jonesga + +EXEC core.fn_dropifexists 'PrimeProblemListTemp', 'onprc_ehr', 'TABLE', NULL; +GO + +EXEC core.fn_dropifexists 'PrimeProblemListMaster', 'onprc_ehr', 'TABLE', NULL; +GO + +EXEC core.fn_dropifexists 'p_CaseToPRoblemListupdates', 'onprc_ehr', 'PROCEDURE', NULL; +GO + +-- Author: R. Blasa +-- Created: 8-30-2023 +-- Description: Stored procedure program to allow cage status settings to be updated by default to "Normal". + + +CREATE Procedure [onprc_ehr].[p_CageStatusupdates] + +AS + +BEGIN + +If exists (select * from ehr_lookups.cage) + BEGIN + --- Set Cage status to Normal ) + + Update ehr_lookups.cage + Set status = 'Normal' + Where status is null + + + If @@Error <> 0 + GoTo Err_Proc + +END + + RETURN 0 + + +Err_Proc: + -------Error Generated + RETURN 1 + + +END + +GO + + +-- Author: R. Blasa +-- Created: 8-30-2023 +-- Description: Temp table for cage information audit history. + +CREATE TABLE [onprc_ehr].[CageAuditLog]( + [searchid] [int] IDENTITY(100,1) NOT NULL, + [rowid] [int] NULL, + [location] [nvarchar](100) NULL, + [room] [varchar](200) NULL, + [cage] [varchar](200) NULL, + [divider] [int] NULL, + [cage_type] [varchar](100) NULL, + [hasTunnel] [bit] NULL, + [status] [varchar](200) NULL, + [Container] [dbo].[ENTITYID] NOT NULL, + [area] [varchar](500) NULL, + [housingtype] [varchar](500) NULL, + [housingcondition] [varchar](500) NULL, + [date_created] [smalldatetime] NULL + ) ON [PRIMARY] + + GO + + + + + + + + + + +-- Author: R. Blasa +-- Created: 8-30-2023 +-- Description: Stored procedure program to provide historical cage information audit history. + + +CREATE Procedure [onprc_ehr].[p_CageAuditHistoryProcess] + +AS + + +BEGIN + + --- Create historical cage data +If exists (select * from onprc_ehr.CageAuditLog) +BEGIN +Insert into onprc_ehr.CageAuditLog +Select rowid, + a.location, + a.room, + a.cage, + a.divider, + a.cage_type, + a.hasTunnel, + a.status, + a.container, + (select h.area from ehr_lookups.rooms h where h.room = a.room) as area, + (select s.value from ehr_lookups.rooms h, ehr_lookups.lookups s where h.room = a.room and s.rowid = h.housingtype) as housingtype, + (select s.value from ehr_lookups.rooms h, ehr_lookups.lookups s where h.room = a.room and s.rowid = h.housingcondition) as housingcondition, + getdate() + +from ehr_lookups.cage a + + If @@Error <> 0 + GoTo Err_Proc + +END --- if exists + + RETURN 0 + + +Err_Proc: + -------Error Generated + RETURN 1 + + +END + +GO + +ALTER TABLE onprc_ehr.CageAuditLog ADD CONSTRAINT pk_searchid PRIMARY KEY (searchid); + +-- ================================================================================================= +-- Add MPA Clinical remarks: By, Lakshmi Kolli +-- Created on: 1/25/2024 +/* Description: Created 1 temp table to store the clinical remarks records. + The stored proc manages the addition and deleting clinical remarks data from the temp table + at the time of execution via ETL process. + */ +-- ================================================================================================= + +--Drop table if exists +EXEC core.fn_dropifexists 'Temp_ClnRemarks','onprc_ehr','TABLE'; +--Drop Stored proc if exists +EXEC core.fn_dropifexists '[onprc_ehr].[MPA_ClnRemarkAddition]', 'onprc_ehr', 'PROCEDURE'; +GO + +-- Create the temp table +CREATE TABLE onprc_ehr.Temp_ClnRemarks +( + date datetime, + qcstate int, + participantid nvarchar(32), + project int, + remark nvarchar(250) , + p nvarchar(250) , + performedby nvarchar(250) , + category nvarchar(250) , + taskid nvarchar(4000), + createdby int, + modifiedby int +) +; + +GO + +-- Create the stored proc +/****** Object: StoredProcedure [onprc_ehr].[MPA_ClnRemarkAddition] Script Date: 1/25/2024 *****/ +-- ================================================================================= + -- Author: Lakshmi Kolli + -- Create date: 1/25/2024 + -- Description: This procedure identifies if an animal received an MPA injection + -- and inserts a clinical remark into animal's record. +-- ================================================================================= + +CREATE PROCEDURE [onprc_ehr].[MPA_ClnRemarkAddition] +AS + +DECLARE +@MPACount Int, + @taskId nvarchar(4000) + +BEGIN + --Delete all rows from the temp_Drug table + Delete From onprc_ehr.Temp_ClnRemarks + + --Check if the MPA injection E-85760 was administered today + Select @MPACount = COUNT(*) From studyDataset.c6d178_drug + Where code = 'E-85760' And CONVERT(DATE, date) = CONVERT(DATE, GETDATE()) And qcstate = 18 + + --Found entries, so, enter the clinical remarks now + If @MPACount > 0 + Begin + -- Create a Task entry in ehr.tasks table + Set @taskid = NEWID() -- creating taskid + Insert Into ehr.tasks + (taskid, category, title, formtype, qcstate, assignedto, duedate, createdby, created, + container, modifiedby, modified, description, datecompleted) + Values + (@taskid, 'Task', 'Bulk Clinical Entry', 'Bulk Clinical Entry', 18, 1003, GETDATE(), 1003, GETDATE(), + 'CD17027B-C55F-102F-9907-5107380A54BE', 1003, GETDATE(), 'Created by the ETL process', GETDATE()) + + --Insert the clinical remark into the temp clinical remarks table. + /* Get all the Animals who had MPA injection today from studyDataset.c6d178_drug + and INSERT the data into the studyDataset.c6d185_clinremarks table */ + Insert Into onprc_ehr.Temp_ClnRemarks ( + date, qcstate, participantid, project, remark, p, performedby, category, taskid, createdby, modifiedby + ) + Select GETDATE(), 18, participantid, project, 'Remark entered by the ETL process', 'MPA injection administered', 'onprcitsupport@ohsu.edu', 'Clinical', @taskId, 1003, 1003 + From studyDataset.c6d178_drug + Where code = 'E-85760' And CONVERT(DATE, date) = CONVERT(DATE, GETDATE()) And qcstate = 18 + End + +END + +GO + +CREATE TABLE onprc_ehr.Environmental_Reference_Data ( + rowId int identity(1,1), + label varchar(250) DEFAULT NULL, + value varchar(500) , + columnName varchar(255) NOT NULL, + sort_order integer null, + endDate datetime DEFAULT NULL, + + CONSTRAINT pk_referenceenv PRIMARY KEY (value) +) + + + GO + +CREATE TABLE onprc_ehr.Environmental_Assessment( + rowid int IDENTITY(100,1) NOT NULL, + date datetime NULL, + service_requested varchar(300) NULL, + charge_unit varchar(300) NULL, + testing_location varchar(300) NULL, + test_type varchar(300) NULL, + test_results varchar(100) NULL, + pass_fail varchar(100) NULL, + biological_Cycle varchar(300) NULL, + biological_BI varchar(300) NULL, + action varchar(300) NULL, + performedby varchar(300) NULL, + remarks varchar(300) NULL, + water_source varchar(300) NULL, + surface_tested varchar(300) NULL, + retest varchar(300) NULL, + colony_count varchar(300) NULL, + test_method varchar(300) NULL, + objectid ENTITYID Not Null, + createdby int NULL, + created datetime NULL, + modifiedby int NULL, + modified datetime NULL, + Container ENTITYID NOT NULL, + taskid entityid, + qcstate int NULL, + formsort int NULL + + + CONSTRAINT PK_assessment PRIMARY KEY (objectid) +) + + GO + +/* +** +** Created by Date +** +** Blasa 4-5-2024 Process to update Environmental Assessment data set ldk file from Production database. +** +** +** +*/ + + +CREATE Procedure onprc_ehr.p_Environmental_Update_Process + + + + AS + + +BEGIN + + IF exists (Select * from [list].[c8754d723_surface_sanitation_minus_rodac_48hr]) +BEGIN + + +Insert into onprc_ehr.Environmental_Assessment + +(date, + testing_location, ----TestSite + service_requested, + test_type, ------TestType + colony_count, ---ColonyCount Before: test_resuls + pass_fail, -----PassFail + performedby, ------Collectedby + action, ----Action + remarks, ----comments + objectid, + created, + createdby, + modified, + modifiedby, + qcstate, + container) + +select date, + TestSite, + 'Sanitation: Contact Plate' , + TestType, + ColonyCount, + PassFail, + CollectedBy, + Action, + comment, + newid(), + getdate(), + 1896, + getdate(), + 1896, + 18, + '98F39B23-5E3B-1037-AFE5-BD25D057100A' +from [list].[c8754d723_surface_sanitation_minus_rodac_48hr] + + + + If @@Error <> 0 + GoTo Err_Proc +END ----- + + + + IF exists (Select * from [list].[c8754d726_h2o_testing]) +BEGIN + +Insert into onprc_ehr.Environmental_Assessment + +(date, + testing_location, ---testing Location + service_requested, + water_source, ----H2OSource, + test_type, ----- Testtype + test_results, ----result + pass_fail, ----PassFail + remarks, + objectid, + created, + createdby, + modified, + modifiedby, + qcstate, + container) + +select date, + TestSite, + 'Sanitation: Water Test', + H2OSource, + TestType, + result, + PassFail, + comment, + newid(), + getdate(), + 1896, + getdate(), + 1896, + 18, + '98F39B23-5E3B-1037-AFE5-BD25D057100A' +from [list].[c8754d726_h2o_testing] + + If @@Error <> 0 + GoTo Err_Proc +END ----- + + IF exists (Select * from list.c8754d795_biological_indicator_log) +BEGIN + +Insert into onprc_ehr.Environmental_Assessment + +(date, + testing_location, ---autoclave + service_requested, + biological_Cycle, ----cycle (if applicable) + biological_BI, ----BI# (for ASA) + pass_fail, ---Pass / Fail + retest , ----Results Read by Before: test_results + action, ----- action + performedby, ----collected by + remarks, + objectid, + created, + createdby, + modified, + modifiedby, + qcstate, + container) + +select date, + autoclave, + 'Sanitation: Bio-indicator', + [cycle (if applicable)], + [BI# (for ASA)], + [Pass / Fail], + [Results Read by], + action, + [Collected By], + comment, + newid(), + getdate(), + 1896, + getdate(), + 1896, + 18, + '98F39B23-5E3B-1037-AFE5-BD25D057100A' + +from list.c8754d795_biological_indicator_log + + If @@Error <> 0 + GoTo Err_Proc +END ----- + + + IF exists (Select * from list.c8754d731_atp_testing) +BEGIN + + ---- Note: ATP Testing is strictly Kati's entries only + + +Insert into onprc_ehr.Environmental_Assessment + +(date, + performedby, ---tech inititals + service_requested, + testing_location, ----Area + surface_tested, --- Surface column before -->biological_reader + pass_fail, --- initial + remarks, ---comments + retest, ----retest column before---->water_source + test_results, -------Lab/Group + action , -----location + objectid, + created, + createdby, + modified, + modifiedby, + qcstate, + container) + +select date, + Tech_Initials, + 'Sanitation: ATP', + area, + Surface, + initial, + comments, + retest, + Lab_Group, + location, + newid(), + getdate(), + 1896, + getdate(), + 1896, + 18, + '98F39B23-5E3B-1037-AFE5-BD25D057100A' +from list.c8754d731_atp_testing + + If @@Error <> 0 + GoTo Err_Proc +END ----- + + + + +RETURN 0 + + + Err_Proc: + RETURN 1 + +END + + GO + + + + + + +/* +** +** Created by Date +** +** Blasa 4-5-2024 Process to update Environmental Assessment data set ldk file from Production database. +** +** +** +*/ + + +CREATE Procedure onprc_ehr.p_EnvironmentalHistoricalUpdates + + + + AS + + +BEGIN + +IF exists (Select * from onprc_ehr.Environmental_Assessment) +BEGIN +---Update Testing location syntax + +Update ss +set ss.testing_location = 'COL SW' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Col. SW' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Annex Rm 1', + ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Annex Rm 1' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'COL SW', + ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Colony SW' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Catch Area 2', + ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Catch 2' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Pens Run 1 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 1' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Pens Run 10 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 10' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Pens Run 11 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 11' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Pens Run 12 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 12' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Pens Run 2 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 2' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Pens Run 3 Lixit' + + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 3' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Pens Run 4 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 4' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Pens Run 5 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 5' + + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Pens Run 6 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 6' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Pens Run 7 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 7' + + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Pens Run 8 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 8' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Pens Run 9 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Pens Run 9' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 1 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 1' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 10 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 10' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 11 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 11' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 12 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 12' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 13 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 13' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 14 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 14' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 15 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 15' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 16 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 16' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'SGH 17 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 17' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 18 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 18' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 19 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 19' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 2 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 2' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 20 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 20' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 21 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 21' + + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'SGH 22 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 22' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 23 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 23' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'SGH 24 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 24' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 25 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 25' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 26 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 26' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 27 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 27' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 28 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 28' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 29 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 29' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 30 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 30' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 3 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 3' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 31 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 31' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 32 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 32' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 4 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 4' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 5 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 5' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 6 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 6' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 7 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 7' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 8 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 8' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 9 Lixit' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 9' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'BOS RM 102' + + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Bosky 102' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'BOS RM 103' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Bosky 103' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'BOS RM 104' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Bosky 104' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'BOS RM 122' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Bosky 122' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'BOS RM 123' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Bosky 123' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Cage Washer Colony Annex toy' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Cage Washer Colony Annex tunnel toy' + + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Cage Washer VGTI Large (Jan/June)' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Cage Washer VGTI Large (semi-annual)' + + + If @@Error <> 0 + GoTo Err_Proc +Update ss +set ss.testing_location = 'Cage Washer VGTI Small (Jan/June)' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Cage Washer VGTI Small (semi-annual)' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Dishwasher Colony North' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Dishwasher N. Colony' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Dishwasher Colony South' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Dishwasher S. Colony' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Annex Rm 37' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Annex room 37' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Catch Area 2' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Catch 2' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Catch Area 5' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Catch 5' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'COL SW' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Col. SW' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'COL NW' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Col. NW' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'COL NW' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Colony NW' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'COL RM 4' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Colony RM 4' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'COL Run 1' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Colony Run 1' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'COL Run 2' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Colony Run 2' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'COL Run 3' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Colony Run 3' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'COL Run 4' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Colony Run 4' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'COL Run 5' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Colony Run 5' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss + set ss.testing_location = 'COL Run 6' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss + where ss.testing_location = 'Colony Run 6' + + + If @@Error <> 0 + GoTo Err_Proc + Update sS + set ss.testing_location = 'COL Run 7' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss + where ss.testing_location = 'Colony Run 7' + + + If @@Error <> 0 + GoTo Err_Proc + + Update ss + set ss.testing_location = 'COL Run 8' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss + where ss.testing_location = 'Colony Run 8' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'COL SW' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Colony SW' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 1' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 1 inside' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'SGH 1' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 1 inside' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'SGH 2' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 2 outside' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 2' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 2 outside' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 29' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 29 inside' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 29' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 29 inside' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 30' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 30 outside' + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'SGH 30' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 30 outside' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Dishwasher Bldg 611 ' + -- ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'SGH 30 outside' + + If @@Error <> 0 + GoTo Err_Proc + +update onprc_ehr.Environmental_Assessment +set testing_location = 'Dishwasher ASA 135' +where testing_location = 'Dishwasher ASA 135 ' + + + If @@Error <> 0 + GoTo Err_Proc + +update onprc_ehr.Environmental_Assessment +set testing_location = 'Dishwasher ASA 136' +where testing_location = 'Dishwasher ASA 136 ' + + If @@Error <> 0 + GoTo Err_Proc + +update onprc_ehr.Environmental_Assessment +set testing_location = 'Dishwasher Bldg 611' +where testing_location = 'Dishwasher Bldg 611 ' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Annex Rm 1' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RM 1' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Annex Rm 34' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RM 34' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Annex Rm 13' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RM 13' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Annex Rm 14' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RM 14' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Annex Rm 15' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RM 15' + + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Annex Rm 16' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RM 16' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Annex Rm 2' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RM 2' + + If @@Error <> 0 + GoTo Err_Proc + + +Update ss +set ss.testing_location = 'Annex Rm 34' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RM 34' + + + If @@Error <> 0 + GoTo Err_Proc +Update ss +set ss.testing_location = 'Annex Rm 39' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RM 39' + + + If @@Error <> 0 + GoTo Err_Proc +Update ss +set ss.testing_location = 'Annex Rm 4' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RM 4' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss + set ss.testing_location = 'Annex Run 1' + from onprc_ehr.Environmental_Assessment ss + where ss.testing_location = 'AN RUN 1' + + + If @@Error <> 0 + GoTo Err_Proc +Update ss +set ss.testing_location = 'Annex Run 2' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RUN 2' + + + If @@Error <> 0 + GoTo Err_Proc +Update ss +set ss.testing_location = 'Annex Run 3' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RUN 3' + + + If @@Error <> 0 + GoTo Err_Proc +Update ss +set ss.testing_location = 'Annex Run 30' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'AN RUN 30' + + + If @@Error <> 0 + GoTo Err_Proc + +Update ss +set ss.testing_location = 'Col Run 7E' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location = 'Col Run 7 E' + + If @@Error <> 0 + GoTo Err_Proc + +------ Update only locations designated as Clinpath locations. + +Update ss +set ss.charge_unit = 'Clinpath' + from onprc_ehr.Environmental_Assessment ss +where ss.testing_location in (select distinct value from onprc_ehr.Environmental_Reference_Data where columnname = 'testlocation') + + If @@Error <> 0 + GoTo Err_Proc + +----------- Update only locations designated as Kati's Room LocationXXXX + +update onprc_ehr.Environmental_Assessment +set testing_location = 'Col Run 7A' +where testing_location = 'Col Run 7 A' + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Col Run 7B' +where testing_location = 'Col Run 7 B' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Col Run 7D' +where testing_location = 'Col Run 7 D' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Colony Rm 2 (Clinic)' +where testing_location = 'Colony Rm 2 Clinic' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Pens RM 102A (Clinic)' +where testing_location = 'Pens Rm 102A (Clinic)' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Pens RM 104 (Feed)' +where testing_location = 'PENS Rm 104 (Feed Room)' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Pens RM 104 (Feed)' +where testing_location = 'Pens RM 104 (Feed )' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'VGTI 0120 (clean cage wash)' +where testing_location = 'VGTI 0120 (clean cage wash' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Col Run 6A' +where testing_location = 'Col Run 6 A' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Col Run 6C' +where testing_location = 'Col Run 6 C' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'ASB 3 Cage Wash' +where testing_location = 'ASB 3 Cage Wash Area' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'ASB 1 Cage Wash' +where testing_location = 'ASB 1 Cage Wash Area' + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Cage Washer ASB 1 cage' +where testing_location = 'Cage Washer ASB 1' + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Cage Washer VGTI Large (Jan/June)' +where testing_location = 'Cage Washer VGTI Large' + + + + If @@Error <> 0 + GoTo Err_Proc +update onprc_ehr.Environmental_Assessment +set testing_location = 'Cage Washer VGTI Small (Jan/June)' +where testing_location = 'Cage Washer VGTI Small' + + + If @@Error <> 0 + GoTo Err_Proc + +END ----if exists + + + +RETURN 0 + + + Err_Proc: + RETURN 1 + +END + +GO + +-- Alter the stored proc +/****** Object: StoredProcedure [onprc_ehr].[MPA_ClnRemarkAddition] Script Date: 5/17/2024 *****/ +-- ================================================================================= +-- Author: Lakshmi Kolli +-- Create date: 5/17/2024 +-- Description: Altering the procedure with the new ONPRC email address +-- ================================================================================= + +ALTER PROCEDURE [onprc_ehr].[MPA_ClnRemarkAddition] +AS + +DECLARE +@MPACount Int, +@taskId nvarchar(4000), +@displayName nvarchar(250) + +BEGIN + --Delete all rows from the temp_Drug table + Delete From onprc_ehr.Temp_ClnRemarks + + --Check if the MPA injection E-85760 was administered today + Select @MPACount = COUNT(*) From studyDataset.c6d178_drug + Where code = 'E-85760' And CONVERT(DATE, date) = CONVERT(DATE, GETDATE()) And qcstate = 18 + + --Found entries, so, enter the clinical remarks now + If @MPACount > 0 + Begin + -- Get the displayName for user: onprc-is from core.users table + Select @displayName = displayName from core.users where userid = 1003 + + -- Create a Task entry in ehr.tasks table + Set @taskid = NEWID() -- creating taskid + Insert Into ehr.tasks + (taskid, category, title, formtype, qcstate, assignedto, duedate, createdby, created, + container, modifiedby, modified, description, datecompleted) + Values + (@taskid, 'Task', 'Bulk Clinical Entry', 'Bulk Clinical Entry', 18, 1003, GETDATE(), 1003, GETDATE(), + 'CD17027B-C55F-102F-9907-5107380A54BE', 1003, GETDATE(), 'Created by the ETL process', GETDATE()) + + --Insert the clinical remark into the temp clinical remarks table. + /* Get all the Animals who had MPA injection today from studyDataset.c6d178_drug + and INSERT the data into the studyDataset.c6d185_clinremarks table */ + Insert Into onprc_ehr.Temp_ClnRemarks ( + date, qcstate, participantid, project, remark, p, performedby, category, taskid, createdby, modifiedby + ) + Select GETDATE(), 18, participantid, project, 'Remark entered by the ETL process', 'MPA injection administered', @displayName, 'Clinical', @taskId, 1003, 1003 + From studyDataset.c6d178_drug + Where code = 'E-85760' And CONVERT(DATE, date) = CONVERT(DATE, GETDATE()) And qcstate = 18 + End +END + +GO + +CREATE TABLE [onprc_ehr].[TB_TestTemp]( + [rowid] [int] IDENTITY(100,1) NOT NULL, + animalid varchar(200) NULL, + date datetime NULL, + objectid ENTITYID NOT NULL, + created datetime NULL, + createdby integer NULL, + performedby varchar(200) NULL + + + ) + GO + +CREATE TABLE [onprc_ehr].[TB_TestTempMaster]( + rowid integer , + animalid varchar(200) NULL, + date datetime NULL, + objectid ENTITYID NOT NULL, + created datetime NULL, + createdby integer NULL, + performedby varchar(200) NULL + + + ) + GO + + + + + +/* +** +** Created by +** R. Blasa 6-5-2024 A Program Process that reviews all TB Test entries on a given date, and creates a +** new TB Test Clinical Observation record based on +** having the same monkey id, date, and to be assigned to a Data Admin for reviews. +** +** +*/ + +CREATE Procedure onprc_ehr.p_Create_TB_Observationrecords + + + + AS + + + +DECLARE + @SearchKey Int, + @TempsearchKey Int, + @TaskId varchar(4000), + @ObjectId varchar(4000), + @AnimalID varchar(100), + @date datetime, + @createdby smallint, + @created smalldatetime, + @performedby varchar(200), + @RunID varchar(4000) + + + + +BEGIN + + + + ---- Reset temp table + +Truncate table onprc_ehr.TB_TestTemp + + + If @@Error <> 0 + GoTo Err_Proc + + + --- Generate a list TB test monkeys ) + + Insert into onprc_ehr.TB_TestTemp + +select + a.participantid, + a.date, + a.objectid, + a.created, + a.createdBy, + a.performedby + + + + +from studydataset.c6d214_encounters a +Where a.participantid not in (select b.participantid from studydataset.c6d171_clinical_observations b + where a.participantid = b.participantid And cast(a.date as date) = dateadd(day,3,cast(b.date as date)) And b.category = 'TB TST Score (72 hr)' ) + And a.type = 'Procedure' And a.qcstate = 18 And procedureid = 802 -----'TB Test Intradermal' + And a.created >= dateadd(day, -1, cast(getdate() as date)) +And a.participantid in ( select k.participantid from studydataset.c6d203_demographics k + where k.calculated_status = 'alive') + +order by a.participantid, a.date desc + + + If @@Error <> 0 + GoTo Err_Proc + + ---- When there are no records to process, exit immediately from the program. + + If (Select count(*) from onprc_ehr.TB_TestTemp) = 0 + +BEGIN +GOTO No_Records +END + + + ---- Reset temp variables + + Set @SearchKey = 0 + Set @TempSearchKey = 0 + Set @Date = NULL + Set @created = NULL + Set @createdby =NULL + Set @performedby = NULL + Set @TaskID = NULL + Set @Animalid = Null + Set @RunID = Null + + + + ----- extract initial row id + +Select Top 1 @Searchkey = rowid from onprc_ehr.TB_TestTemp +Order by rowid + + + While @TempSearchKey < @SearchKey +BEGIN + + -----Begin entry Tb observation process + +Select @Animalid =animalid, @date = date, @created =created, @createdby =createdby,@performedby= performedby from onprc_ehr.TB_TestTemp Where rowid = @Searchkey + + If not exists (select * from studydataset.c6d171_clinical_observations j Where j.participantid = @AnimalID + And cast(j.date as date) = dateadd(day,3,cast(@date as date)) And j.category = 'TB TST Score (72 hr)' ) +BEGIN + + + + Set @TaskID = NEWID() ----- Task Record Object ID + Set @RunID = NEWID() ---- ObjectID + Set @date = dateadd(day, 3,@date) ----- Add three days from TB Test date + + + + ---- Generate a Task id record + + Insert into EHR.Tasks + ( + taskid, + description, + title, + qcstate, + formType, + category, + container, + assignedto, + created, + createdby, + modified, + modifiedby + + ) + + Values ( + + @TaskID, + @AnimalID + ' ' + cast(@Date as varchar(50)) , ------ Title consist of animal id and Clinical procedure date + 'TB TST Scores', + 20, --- Qc State (In Progress) + 'TB TST Scores', ------ FormType + 'task', ----- category, + 'CD17027B-C55F-102F-9907-5107380A54BE', ---- EHR Container + 1822, -------- Assigned To Data Admins + getdate(), ------- Create Date + @createdby, -------- Created By + getdate(), ------- Modified Date + @createdby ----- Modified by + + ) + + If @@Error <> 0 + GoTo Err_Proc + + + + --- Create a Clinical Observation Record + + Insert into studydataset.c6d171_clinical_observations + ( + participantid, + date, + category, + area, + observation, + created, + createdby, + performedby, + objectid, + taskid, + qcstate, + modified, + modifiedby, + lsid + + ) + values ( + @animalid, + @date, + 'TB TST Score (72 hr)', + 'Right Eyelid', + 'Grade: Negative', + getdate(), ----- created + @createdby, + @performedby, + @RunID , ----- Objectid + @TaskID, + 20 , ---- In Progress QCState + getdate(), -----modified + @createdBy, + 'urn:lsid:ohsu.edu:Study.Data-6:5006.10003.19810204.0000.' + '' + @RunID + '' + + ) + + If @@Error <> 0 + GoTo Err_Proc + + + +END + + + ----- Proceed and fetch the next record + + Set @TempSearchKey = @SearchKey + +Select Top 1 @SearchKey = rowid from onprc_ehr.TB_TestTemp +Where rowid > @TempSearchKey +Order by rowid + + +END ---- While @TempSearchKey + + + ----- Create a master copy of the completed transaction + + Insert into onprc_ehr.TB_TestTempMaster + Select * from onprc_ehr.TB_TestTemp + + If @@Error <> 0 + GoTo Err_Proc + + + +No_Records: + + RETURN 0 + + +Err_Proc: + -------Error Generated, program processed stopped + RETURN 1 + + +END + +GO + +/* +** +** Created by +** R. Blasa 6-5-2024 A Program Process that reviews all TB Test entries on a given date, and creates a +** new TB Test Clinical Observation record based on +** having the same monkey id, date, and to be assigned to a Data Admin for reviews. +** +** R. Blasa Modified program so that each Clinical Observation entries generated by the program is assigned +** only a single task id when the program executes daily. +** +** +*/ + + ALTER Procedure onprc_ehr.p_Create_TB_Observationrecords + + + + AS + + + +DECLARE + @SearchKey Int, + @TempsearchKey Int, + @TaskId varchar(4000), + @ObjectId varchar(4000), + @AnimalID varchar(100), + @date datetime, + @createdby smallint, + @created smalldatetime, + @performedby varchar(200), + @RunID varchar(4000) + + + + +BEGIN + + + + ---- Reset temp table + +Truncate table onprc_ehr.TB_TestTemp + + + If @@Error <> 0 + GoTo Err_Proc + + + --- Generate a list TB test monkeys ) + + Insert into onprc_ehr.TB_TestTemp + +select + a.participantid, + a.date, + a.objectid, + a.created, + a.createdBy, + a.performedby + + + + +from studydataset.c6d214_encounters a +Where a.participantid not in (select b.participantid from studydataset.c6d171_clinical_observations b + where a.participantid = b.participantid And cast(a.date as date) = dateadd(day,3,cast(b.date as date)) And b.category = 'TB TST Score (72 hr)' ) + And a.type = 'Procedure' And a.qcstate = 18 And procedureid = 802 -----'TB Test Intradermal' + And a.created >= dateadd(day, -1, cast(getdate() as date)) +And a.participantid in ( select k.participantid from studydataset.c6d203_demographics k + where k.calculated_status = 'alive') + +order by a.participantid, a.date desc + + + If @@Error <> 0 + GoTo Err_Proc + + ---- When there are no records to process, exit immediately from the program. + + If (Select count(*) from onprc_ehr.TB_TestTemp) = 0 + BEGIN + GOTO No_Records + END + + + ---- Reset temp variables + + Set @SearchKey = 0 + Set @TempSearchKey = 0 + Set @Date = NULL + Set @created = NULL + Set @createdby =NULL + Set @performedby = NULL + Set @TaskID = NULL + Set @Animalid = Null + Set @RunID = Null + + + + ----- extract initial row id + + Select Top 1 @Searchkey = rowid from onprc_ehr.TB_TestTemp + Order by rowid + + + Set @TaskID = NEWID() ----- Task Record Object ID + + ----Create a single task for each daily process + + + Insert into EHR.Tasks + ( + taskid, + description, + title, + qcstate, + formType, + category, + container, + assignedto, + created, + createdby, + modified, + modifiedby + + ) + + Values ( + + @TaskID, + 'TB TST Scores ' + cast(@Date as varchar(50)) , ------ Title consist of animal id and Clinical procedure date + 'TB TST Scores', + 20, --- Qc State (In Progress) + 'TB TST Scores', ------ FormType + 'task', ----- category, + 'CD17027B-C55F-102F-9907-5107380A54BE', ---- EHR Container + 1822, -------- Assigned To Data Admins + getdate(), ------- Create Date + 1042, -------- Created By IS + getdate(), ------- Modified Date + 1042 ----- Modified by IS + + ) + + If @@Error <> 0 + GoTo Err_Proc + + + + While @TempSearchKey < @SearchKey + BEGIN + + -----Begin entry Tb observation process + + Select @Animalid =animalid, @date = date, @created =created, @createdby =createdby,@performedby= performedby from onprc_ehr.TB_TestTemp Where rowid = @Searchkey + + If not exists (select * from studydataset.c6d171_clinical_observations j Where j.participantid = @AnimalID + And cast(j.date as date) = dateadd(day,3,cast(@date as date)) And j.category = 'TB TST Score (72 hr)' ) + BEGIN + + + + ----- Initialize data entries + Set @RunID = NEWID() ---- ObjectID + Set @date = dateadd(day, 3,@date) ----- Add three days from TB Test date + + + + --- Create a Clinical Observation Record + + Insert into studydataset.c6d171_clinical_observations + ( + participantid, + date, + category, + area, + observation, + created, + createdby, + performedby, + objectid, + taskid, + qcstate, + modified, + modifiedby, + lsid + + ) + values ( + @animalid, + @date, + 'TB TST Score (72 hr)', + 'Right Eyelid', + 'Grade: Negative', + getdate(), ----- created + @createdby, + @performedby, + @RunID , ----- Objectid + @TaskID, + 20 , ---- In Progress QCState + getdate(), -----modified + @createdBy, + 'urn:lsid:ohsu.edu:Study.Data-6:5006.10003.19810204.0000.' + '' + @RunID + '' + + ) + + If @@Error <> 0 + GoTo Err_Proc + + + +END + + + ----- Proceed and fetch the next record + + Set @TempSearchKey = @SearchKey + +Select Top 1 @SearchKey = rowid from onprc_ehr.TB_TestTemp +Where rowid > @TempSearchKey +Order by rowid + + +END ---- While @TempSearchKey + + + ----- Create a master copy of the completed transaction + + Insert into onprc_ehr.TB_TestTempMaster + Select * from onprc_ehr.TB_TestTemp + + If @@Error <> 0 + GoTo Err_Proc + + + +No_Records: + + RETURN 0 + + +Err_Proc: + -------Error Generated, program processed stopped + RETURN 1 + + +END + +GO + +/* +** +** Created by +** R. Blasa 6-5-2024 A Program Process that reviews all TB Test entries on a given date, and creates a +** new TB Test Clinical Observation record based on +** having the same monkey id, date, and to be assigned to a Data Admin for reviews. +** +** R. Blasa Modified program so that each Clinical Observation entries generated by the program is assigned +** only a single task id when the program executes daily. +** +** +*/ + + ALTER Procedure onprc_ehr.p_Create_TB_Observationrecords + + + + AS + + + +DECLARE + @SearchKey Int, + @TempsearchKey Int, + @TaskId varchar(4000), + @ObjectId varchar(4000), + @AnimalID varchar(100), + @date datetime, + @createdby smallint, + @created smalldatetime, + @performedby varchar(200), + @RunID varchar(4000) + + + + +BEGIN + + + + ---- Reset temp table + +Truncate table onprc_ehr.TB_TestTemp + + + If @@Error <> 0 + GoTo Err_Proc + + + --- Generate a list TB test monkeys ) + + Insert into onprc_ehr.TB_TestTemp + +select + a.participantid, + a.date, + a.objectid, + a.created, + a.createdBy, + a.performedby + + + + +from studydataset.c6d214_encounters a +Where a.participantid not in (select b.participantid from studydataset.c6d171_clinical_observations b + where a.participantid = b.participantid + And cast(b.date as date) = dateadd(day,3,cast(a.date as date)) + And b.category = 'TB TST Score (72 hr)' + And a.created >= cast(getdate() as date) + And a.type = 'Procedure' And a.qcstate = 18 And a.procedureid = 802 ) + + And a.type = 'Procedure' And a.qcstate = 18 And a.procedureid = 802 -----'TB Test Intradermal' + And a.created >= cast(getdate() as date) +And a.participantid in ( select k.participantid from studydataset.c6d203_demographics k + where k.calculated_status = 'alive') + +order by a.participantid, a.date desc + + + If @@Error <> 0 + GoTo Err_Proc + + ---- When there are no records to process, exit immediately from the program. + + If (Select count(*) from onprc_ehr.TB_TestTemp) = 0 + BEGIN + GOTO No_Records + END + + + ---- Reset temp variables + + Set @SearchKey = 0 + Set @TempSearchKey = 0 + Set @Date = NULL + Set @created = NULL + Set @createdby =NULL + Set @performedby = NULL + Set @TaskID = NULL + Set @Animalid = Null + Set @RunID = Null + + + + ----- extract initial row id + + Select Top 1 @Searchkey = rowid from onprc_ehr.TB_TestTemp + Order by rowid + + + Set @TaskID = NEWID() ----- Task Record Object ID + + ----Create a single task for each daily process + + + Insert into EHR.Tasks + ( + taskid, + description, + title, + qcstate, + formType, + category, + container, + assignedto, + created, + createdby, + modified, + modifiedby + + ) + + Values ( + + @TaskID, + 'TB TST Scores ' + cast(@Date as varchar(50)) , ------ Title consist of animal id and Clinical procedure date + 'TB TST Scores', + 20, --- Qc State (In Progress) + 'TB TST Scores', ------ FormType + 'task', ----- category, + 'CD17027B-C55F-102F-9907-5107380A54BE', ---- EHR Container + 1822, -------- Assigned To Data Admins + getdate(), ------- Create Date + 1042, -------- Created By IS + getdate(), ------- Modified Date + 1042 ----- Modified by IS + + ) + + If @@Error <> 0 + GoTo Err_Proc + + + + While @TempSearchKey < @SearchKey + BEGIN + + -----Begin entry Tb observation process + + Select @Animalid =animalid, @date = date, @created =created, @createdby =createdby,@performedby= performedby from onprc_ehr.TB_TestTemp Where rowid = @Searchkey + + If not exists (select * from studydataset.c6d171_clinical_observations j Where j.participantid = @AnimalID + And cast(j.date as date) = dateadd(day,3,cast(@date as date)) And j.category = 'TB TST Score (72 hr)' ) + BEGIN + + + + ----- Initialize data entries + Set @RunID = NEWID() ---- ObjectID + Set @date = dateadd(day, 3,@date) ----- Add three days from TB Test date + + + + --- Create a Clinical Observation Record + + Insert into studydataset.c6d171_clinical_observations + ( + participantid, + date, + category, + area, + observation, + created, + createdby, + performedby, + objectid, + taskid, + qcstate, + modified, + modifiedby, + lsid + + ) + values ( + @animalid, + @date, + 'TB TST Score (72 hr)', + 'Right Eyelid', + 'Grade: Negative', + getdate(), ----- created + @createdby, + @performedby, + @RunID , ----- Objectid + @TaskID, + 20 , ---- In Progress QCState + getdate(), -----modified + @createdBy, + 'urn:lsid:ohsu.edu:Study.Data-6:5006.10003.19810204.0000.' + '' + @RunID + '' + + ) + + If @@Error <> 0 + GoTo Err_Proc + + + +END + + + ----- Proceed and fetch the next record + + Set @TempSearchKey = @SearchKey + +Select Top 1 @SearchKey = rowid from onprc_ehr.TB_TestTemp +Where rowid > @TempSearchKey +Order by rowid + + +END ---- While @TempSearchKey + + + ----- Create a master copy of the completed transaction + + Insert into onprc_ehr.TB_TestTempMaster + Select * from onprc_ehr.TB_TestTemp + + If @@Error <> 0 + GoTo Err_Proc + + + +No_Records: + + RETURN 0 + + +Err_Proc: + -------Error Generated, program processed stopped + RETURN 1 + + +END + +GO + +/* 24.xxx SQL scripts */ + +--added to allow insert of calculated fields from eIACUC + +--2024-12-13 In development need to use a drop if exists statement for these to run + +ALTER TABLE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS ADD [BaseProtocol] varchar(100) Null; +ALTER TABLE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS ADD [RevisionNumber] varchar(100) Null; +ALTER TABLE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS ADD [NewestRecord] INT Null; + +GO + +CREATE PROCEDURE onprc_ehr.BaseProtocol +AS +BEGIN + -- Create a Common Table Expression (CTE) named BaseProtocol + WITH BaseProtocol AS + ( + SELECT + RowID, + Protocol_id, + -- Determine the BaseProtocol based on the length of the Protocol_id + CASE + WHEN LEN(Protocol_id) > 10 THEN SUBSTRING(Protocol_id, 6, 15) + ELSE Protocol_id + END AS BaseProtocol, + -- Determine the RevisionNumber based on the length of the Protocol_id + CASE + WHEN LEN(Protocol_id) > 10 THEN SUBSTRING(Protocol_id,1, 5) + ELSE 'Original' + END AS RevisionNumber, + approval_date, + Three_Year_Expiration, + last_modified, + Protocol_State + FROM onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS + ) + + -- Update the onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS table with BaseProtocol and RevisionNumber from the CTE + UPDATE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS + SET BaseProtocol = BaseProtocol.BaseProtocol, + RevisionNumber = BaseProtocol.RevisionNumber + FROM BaseProtocol + WHERE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS.RowID = BaseProtocol.RowID; +END +GO + +GO +/****** Object: StoredProcedure [onprc_ehr].[ExpiredProtocolUpdate] Script Date: 12/20/2024 9:09:09 AM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE PROCEDURE [onprc_ehr].[ExpiredProtocolUpdate] + AS +BEGIN + +WITH ApprovedProtocols AS ( + SELECT + BaseProtocol, + MAX(Approval_Date) AS maxApprovalDate + FROM + onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS + WHERE + Protocol_State IN ('approved','expired', 'terminated') + GROUP BY + BaseProtocol +), + + + DistinctProtocols AS ( + SELECT DISTINCT + p.rowID, + p.BaseProtocol, + p.RevisionNumber, + p.Protocol_State, + p.Approval_Date, + p.Last_Modified, + p.Three_Year_Expiration + FROM + onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS p + INNER JOIN ApprovedProtocols ap ON p.BaseProtocol = ap.BaseProtocol + AND p.Approval_Date = ap.maxApprovalDate), + ExpiredProtocol AS ( + Select + d.*, + p.protocol, + p.enddate + from DistinctProtocols d inner join ehr.protocol p on d.BaseProtocol = p.external_ID + where d.Protocol_State != 'Approved' and p.enddate is Null) + +Update p + Set p.enddate = getDate() + from ehr.protocol p inner join expiredProtocol e on p.external_id = e.BaseProtocol +END + +GO + +CREATE TABLE onprc_ehr.procedure_default_blood ( + rowid int identity(1,1), + procedureid int, + sampletype varchar(300) Null, + additionalServices varchar(1000) Null, + reason varchar(300) Null, + instructions varchar(2000) Null, + chargetype varchar(400) Null + + + CONSTRAINT PK_procedure_default_blood PRIMARY KEY (rowid) +) + +GO + +CREATE TABLE [onprc_ehr].[Rpt_AnimalID_Weights]( + searchid int IDENTITY(100,1) NOT NULL, + animalID varchar(100) NULL, + date smalldatetime NULL, + weight decimal(12,5) NULL, + taskId ENTITYID NULL, + created smalldatetime NULL, + createdby smallint NULL, + modified smalldatetime NULL, + modifiedby smallint NULL + + ) ON [PRIMARY] + + GO + + +CREATE TABLE [onprc_ehr].[Rpt_AnimalID_WeightsMaster]( + searchid int IDENTITY(100,1) NOT NULL, + rowid int, + animalID varchar(100) NULL, + date smalldatetime NULL, + weight decimal(12,5) NULL, + taskId ENTITYID NULL, + created smalldatetime NULL, + createdby smallint NULL, + modified smalldatetime NULL, + modifiedby smallint NULL, + actual_created smalldatetime NULL, + remark varchar(1000) NULL + + ) ON [PRIMARY] + + GO + + +/* +** +** Created by Date +** +** Blasa 1-29-2025 Extract the Pathology Tissue Weights from Pathology Tissue records. +** +** T-00010 BODY AS A WHOLE Tissue_Samples data set +** +** +** +** +** +** +** +*/ + + +CREATE Procedure onprc_ehr.sp_PathologyTissueWeightsProcess + @StartDate SmallDateTime, + @EndDate SmallDateTime + + + + + AS + + + +DECLARE @ReturnValue Int, + @SearchKey Int, + @TempsearchKey Int, + @AnimalID varchar(100), + @Date smalldatetime, + @RunID varchar(4000) + + +Begin + + + ----- Reset Temp Table + + Set @Returnvalue = 0 + + + ----- Reset Temp tables + Delete onprc_ehr.Rpt_AnimalID_Weights + + + If @@Error <> 0 + GoTo Err_Proc + + + + Insert into onprc_ehr.Rpt_AnimalID_Weights +select + e.participantid, + e.date, + e.weight, + e.taskid, + e.created, + e.createdby, + e.modified, + e.modifiedby + + +from studydataset.c6d174_tissue_samples e +where e.tissue = 'T-00010' + And (e.date >= @StartDate And e.date < Dateadd(day,1,@EndDate) ) + + and e.qcstate = 18 + and e.weight is not null +order by date desc + + + + + If @@Error <> 0 + GoTo Err_Proc + + +Set @TempsearchKey = 0 +Set @SearchKey = 0 + +Select Top 1 @Searchkey = Searchid from onprc_ehr.Rpt_AnimalID_Weights +Order by SearchID + + + + + + While @TempSearchKey < @SearchKey + Begin + + ---- Reset temp variables + Set @AnimalID = null + Set @Date = null + Set @RunID = null + + ----Extract primary weights data from Pathology records + + Select @Animalid = animalid, @Date = date from onprc_ehr.Rpt_AnimalID_Weights where searchid = @Searchkey + + ---- Create Weights entries + + If not exists(select * from studydataset.c6d175_weight + Where participantid = @AnimalID And date = @Date ) + + + Begin + ----- Set record object id + Set @RunID = NEWID() + + Insert into studydataset.c6d175_weight + (participantid, + date, + weight, + qcstate, + created, + createdby, + modified, + modifiedby, + taskid, + objectid, + remark, + lsid + ) + + Select @AnimalID, + @Date, + Rpt.weight/1000, ----- convert weight from grams to Kilograms + 18, ------ default QC State + Rpt.created, + Rpt.createdby, + Rpt.modified, + Rpt.modifiedby, + Rpt.taskid, + @RunID, ------- record object id + 'Weight added from Path Tissue records', + ' urn:lsid:ohsu.edu:Study.Data-6:1045.' + @AnimalID + '.' + format(cast(@date as date), 'yyyyMMdd') + '.0000.' + @RunID + '' + + + + from onprc_ehr.Rpt_AnimalID_Weights Rpt + where searchid = @Searchkey + + If @@Error <> 0 + GoTo Err_Proc + + + + End ---- + + + + + Set @TempSearchkey = @SearchKey + + + Select Top 1 @Searchkey = Searchid from onprc_ehr.Rpt_AnimalID_Weights + Where Searchid > @TempSearchkey + Order by Searchid + + + + + End -----(While) + + ------- Create a Master log of entries + + Insert into onprc_ehr.Rpt_AnimalID_WeightsMaster + Select j.*, + getdate(), ---- record created date + 'Pathology Tissue Weight entry' + + from onprc_ehr.Rpt_AnimalID_Weights j + + + RETURN 0 + +Err_Proc: + + Return 1 + + +END + +GO + +-- ======================================================================================================================================= +-- Author: Lakshmi Kolli +-- Create date: 2025-03-04 +-- Description: Db tables creation for Prima cassette project. Created all the Prima tables in Prime onprc_ehr schema folder. +-- Refer to tkt #11937 +-- ======================================================================================================================================= + +--Drop if exists. We are using these 4 tables for the Cassette Project +EXEC core.fn_dropifexists 'Prima_Animals','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_CassetteBases','onprc_ehr','TABLE'; -- Drop this table and create again +EXEC core.fn_dropifexists 'Prima_TissueCollections','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_CaseBase','onprc_ehr','TABLE'; -- Drop this table and create again + +--Drop these tables permanently. We are not using these tables in onprc_ehr. +EXEC core.fn_dropifexists 'Prima_VeterinaryResearchCase','onprc_ehr','TABLE'; --This table doesn't exist anymore in Prima DB +EXEC core.fn_dropifexists 'Prima_CassetteEvents','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_CassetteEventLocations','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_LabstationTypes','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SlideBases','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SlideEvents','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SlideEventLocations','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_StainTests','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_SurgicalWheels','onprc_ehr','TABLE'; +EXEC core.fn_dropifexists 'Prima_UserPersons','onprc_ehr','TABLE'; + +GO + +--Create tables +--1. Animals table +/****** Object: Table [onprc_ehr].[Prima_Animals] ******/ +CREATE TABLE [onprc_ehr].[Prima_Animals]( + [Id] [int] NOT NULL, + [AlternateIdentifier] [nvarchar](63) NULL, + [BreedId] [int] NULL, + [DateOfBirth] [datetime] NULL, + [FecesId] [int] NULL, + [Gender] [tinyint] NOT NULL, + [GeneTarget] [nvarchar](127) NULL, + [GeneticLine] [nvarchar](127) NULL, + [Genotype] [nvarchar](127) NULL, + [Identifier] [nvarchar](127) NULL, + [MannerOfDeathId] [int] NULL, + [RoomNumber] [nvarchar](9) NULL, + [SpeciesId] [int] NOT NULL, + [StomachContentsId] [int] NULL, + [StrainId] [int] NULL, + [DateOfDeath] [datetime] NULL, + [Created] [datetimeoffset](7) NOT NULL, + [OwnerId] [int] NULL, + [Perfuse] [bit] NOT NULL, + [SampleType] [tinyint] NOT NULL + ) +; + +--2. TissueCollections table +/****** Object: Table [onprc_ehr].[Prima_TissueCollections] ******/ +CREATE TABLE [onprc_ehr].[Prima_TissueCollections]( + [Id] [int] NOT NULL, + [Constant] [tinyint] NULL, + [IsWholeAnimal] [bit] NOT NULL, + [SpeciesId] [int] NOT NULL, + [SpecimenType] [int] NOT NULL, + [CreatedByUserId] [int] NOT NULL, + [Deleted] [datetimeoffset](7) NULL, + [DeletedByUserId] [int] NULL, + [NextVersionId] [int] NULL, + [PreviousVersionId] [int] NULL, + [Title] [nvarchar](127) NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [LastModified] [timestamp] NOT NULL, + [Abbreviation] [nvarchar](127) NULL + ) +; + +--3. CaseBase table +/****** Object: Table [onprc_ehr].[Prima_CaseBase] ******/ +CREATE TABLE [onprc_ehr].[Prima_CaseBase]( + [Id] [int] NOT NULL, + [DifferentialDiagnosisId] [int] NULL, + [PathologistId] [int] NULL, + [PriorityLevelId] [int] NOT NULL, + [ResidentPathologistId] [int] NULL, + [SerialNumber] [int] NOT NULL, + [SurgeryDate] [datetime] NULL, + [SurgicalWheelId] [int] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [ResearcherId] [int] NULL, + [StudyId] [int] NULL, + [Discriminator] [nvarchar](128) NULL, + [StudyPhaseId] [int] NULL, + [CohortId] [int] NULL, + [SavedIdentifier] [nvarchar](max) NULL, + [Status] [tinyint] NOT NULL, + [AlternateIdentifier] [nvarchar](24) NULL, + [SurgeryLocationId] [int] NULL, + [ResearchPatientId] [int] NULL, + [AnimalId] [int] NULL, + [ClinicalPatientId] [int] NULL, + [SurgeryAge] [nvarchar](31) NULL + ) +; + +--4. CassetteBases table +/****** Object: Table [onprc_ehr].[Prima_CassetteBases] ******/ +CREATE TABLE [onprc_ehr].[Prima_CassetteBases]( + [Id] [bigint] NOT NULL, + [CassetteColorId] [int] NOT NULL, + [EmbeddingInstructionId] [int] NOT NULL, + [HasTissue] [bit] NOT NULL, + [ProtocolCassetteId] [int] NULL, + [SpecimenBaseId] [bigint] NOT NULL, + [TissueCollectionId] [int] NULL, + [TissueProcessorProgramId] [int] NULL, + [TissueQuantity] [smallint] NOT NULL, + [CaseBaseId] [int] NOT NULL, + [PriorityLevelId] [int] NOT NULL, + [QcStatus] [tinyint] NOT NULL, + [SurgicalSerialPart] [smallint] NOT NULL, + [Created] [datetimeoffset](7) NOT NULL, + [OrderedStatus] [tinyint] NOT NULL, + [SavedIdentifier] [nvarchar](24) NULL, + [BarcodeContent] [nvarchar](72) NULL, + [AlternateIdentifier] [nvarchar](63) NULL, + [PrintStatus] [tinyint] NOT NULL, + [ItemStatus] [smallint] NOT NULL, + [Hazard] [tinyint] NOT NULL, + [CurrentContainerId] [int] NULL + ) +; + +GO + +CREATE TABLE onprc_ehr.Rpt_AnimalIDTissues( + [Searchkey] [int] IDENTITY(1,1) NOT NULL, + [animalID] varchar(100) NULL, + [date] smalldatetime NULL + + + ) ON [PRIMARY] + GO + +CREATE TABLE onprc_ehr.Rpt_AnimalIDTissues_Master( + [rowid] [int] IDENTITY(1,1) NOT NULL, + [SearchID] int NULL, + [animalID] varchar(100) NULL, + [date] smalldatetime NULL, + [actual_Created] smalldatetime NUll, + [remarks] varchar(500) + + + ) ON [PRIMARY] + GO + + + +/* +** +** Created by Date +** +** Blasa 4/4/2025 Process to attached Tissues Distribution records to Patholody Tissue records +** +** + +** +** +** +** +** + +** +** +** +*/ + + +CREATE Procedure [onprc_ehr].[sp_RptNecropsyTissueDistributionUpdates] + @StartDate SmallDateTime, + @EndDate SmallDateTime + + + + +AS + + + +DECLARE @ReturnValue Int, + @SearchKey Int, + @TempsearchKey Int, + @TaskId varchar(4000), + @ObjectId Varchar(4000), + @AnimalID varchar(100), + @Date smalldatetime, + @Created smalldatetime, + @Createdby smallint, + @modified smalldatetime, + @modifiedby smallint , + @RunID varchar(4000) + +Begin + + + ----- Reset Temp Table + + Set @Returnvalue = 0 + + + + Delete onprc_ehr.Rpt_AnimalIDTissues + + + If @@Error <> 0 + GoTo Err_Proc + + + ----Create the set of records to process + + Insert into onprc_ehr.Rpt_AnimalIDTissues + select distinct + e.participantid, + e.date + + +from studydataset.c6d265_tissuedistributions e + +Where (e.date >= @StartDate And e.date < Dateadd(day,1,@EndDate) ) + And e.qcstate = 18 +order by e.participantid, e.date + + + + If @@Error <> 0 + GoTo Err_Proc + + + +Set @TempsearchKey = 0 +Set @SearchKey = 0 +Set @TaskID = null + +Select Top 1 @Searchkey = Searchkey from onprc_ehr.Rpt_AnimalIDTissues +Order by Searchkey + + + While @TempSearchKey < @SearchKey +Begin + + ------ Create a task record + + Set @TaskID = NEWID() + + + Insert into EHR.Tasks + ( + taskid, + description, + title, + qcstate, + formType, + category, + container, + assignedto, + created, + createdby, + modified, + modifiedby + + ) + + Values ( + + @TaskID, + 'Path Tissues ' + cast(@Date as varchar(50)) , ------ Title + 'PathologyTissues', + 18, --- Qc State (In Progress) + 'PathologyTissues', ------ FormType + 'task', ----- category, + 'CD17027B-C55F-102F-9907-5107380A54BE', ---- EHR Container + 1693, -------- Assigned To DCM Pathology + getdate(), ------- Created Date + 1042, -------- Created By IS + getdate(), ------- Modified Date + 1042 ----- Modified by IS + + ) + + If @@Error <> 0 + GoTo Err_Proc + + + +Select @AnimalID = rpt.AnimalID, @Date= rpt.date, @Created=TDS.created, @Createdby= TDS.createdby, @modified = TDS.modified +from studydataset.c6d265_tissuedistributions TDS, onprc_ehr.Rpt_AnimalIDTissues Rpt +Where TDS.participantid = Rpt.AnimalID + And TDS.date = RPT.date And Rpt.searchkey = @Searchkey + + +If exists (Select * from studydataset.c6d265_tissuedistributions Where participantid = @AnimalID And date = @date) +Begin + Update TDS + set TDS.taskid = @TaskID + + from studydataset.c6d265_tissuedistributions TDS +Where TDS.participantid = @AnimalID + And TDS.date = @Date + + + If @@Error <> 0 + GoTo Err_Proc + +End -- + + + Set @TempSearchkey = @SearchKey + + +Select Top 1 @Searchkey = Searchkey from onprc_ehr.Rpt_AnimalIDTissues +Where Searchkey > @TempSearchkey +Order by Searchkey + + +End -----(While) + + ------- Create a audit records + +Insert into onprc_ehr.Rpt_AnimalidTissues_Master +Select *, + getdate(), + 'Tissue Distribution entries' +from onprc_ehr.Rpt_AnimalIDTissues + + + RETURN 0 + +Err_Proc: + + Return 1 + + +END + +GO + +CREATE TABLE onprc_ehr.snomed_counter +( + subset nvarchar(255) NOT NULL, + count integer NOT NULL, + prefix nvarchar(10) NOT NULL, + container entityid, + createdby userid, + created DATETIME, + modifiedby userid, + modified DATETIME, + + CONSTRAINT pk_snomed_counter PRIMARY KEY (subset), + CONSTRAINT fk_onprc_snomed_counter_container FOREIGN KEY (container) REFERENCES core.Containers (EntityId) +) + +CREATE TABLE onprc_ehr.CenterProjectsTemp( + [searchid] [int] IDENTITY(100,1) NOT NULL, + [project] [smallint] NULL, + [protocol] [smallint] NULL, + [account] [varchar](1000) NULL, + [title] [varchar](2000) NULL, + [research] [smallint] NULL, + [createdby] [smallint] NULL, + [created] [datetime] NULL, + [modified] [datetime] NULL, + [modifiedby] [smallint] NULL, + [startdate] [datetime] NULL, + [enddate] [datetime] NULL, + [displayname] [varchar](1000) NULL, + [investigatorid] [smallint] NULL, + [use_category] [varchar](500) NULL, + [projecttype] [varchar](500) NULL, + [objectid] [varchar](max) NULL, + [date_posted] [datetime] NULL + + ) ON [PRIMARY] + GO + + +/* +** +** Created by +** Blasa 5/31/2025 Process to create Center Projects historical records. First create a complete set +** of currently active records, and after the intitial date, just create a record of entries that +** was recently modified. +** + +** +** +** +** +*/ + +CREATE Procedure onprc_ehr.p_CenterProjectsHistoricalProcess + @InitialDate smalldatetime + + + AS + +BEGIN + + ----- Create a fulle record once only + +IF (cast(getdate() as date) = @InitialDate ) +BEGIN + Insert into onprc_ehr.CenterProjectsTemp + ( + project, + protocol, + account, + title, + research, + createdby, + created, + modified, + modifiedby, + startdate, + enddate, + displayname, + investigatorid, + use_category, + projecttype, + objectid, + date_posted +) + +Select + project, + protocol, + account, + title, + research, + createdby, + created, + modified, + modifiedby, + startdate, + enddate, + name, -----displayname + investigatorid, + use_category, + projecttype, + objectid, + getdate() + + From ehr.project where (enddate is null or enddate >= getdate()) + order by modified + + END + + If @@Error <> 0 + GoTo Err_Proc + + + ------ Create modiified records +if exists(Select * from ehr.project where (enddate is null or enddate >= getdate()) + And modified >= cast(getdate() as date)) +BEGIN + + Insert into onprc_ehr.CenterProjectsTemp + ( + project, + protocol, + account, + title, + research, + createdby, + created, + modified, + modifiedby, + startdate, + enddate, + displayname, + investigatorid, + use_category, + projecttype, + objectid, + date_posted + ) + +Select + project, + protocol, + account, + title, + research, + createdby, + created, + modified, + modifiedby, + startdate, + enddate, + name, -----displayname + investigatorid, + use_category, + projecttype, + objectid, + getdate() + +From ehr.project where (enddate is null or enddate >= getdate()) + And modified >= cast(getdate() as date) +order by modified + + + + If @@Error <> 0 + GoTo Err_Proc + +END ----if + + + RETURN 0 + + +Err_Proc: + -------Error Generated, Transfer process stopped + RETURN 1 + + +END + +GO + +ALTER TABLE onprc_ehr.CenterProjectsTemp ALTER COLUMN protocol VARCHAR(400); +GO + +CREATE TABLE onprc_ehr.pairing_observation_types ( + rowid [int] IDENTITY(100,1) NOT NULL, + value nvarchar(200), + category nvarchar(200), + editorconfig NVARCHAR(MAX), + schemaname nvarchar(200), + queryname nvarchar(200), + valuecolumn nvarchar(200), + Created datetime, + CreatedBy USERID, + Modified datetime, + ModifiedBy USERID, + Container entityId NOT NULL, + + CONSTRAINT PK_ONPRC_EHR_PAIRING_OBSERVATION_TYPES PRIMARY KEY (rowid), + +); +GO + +/* +** +** Created by +** Blasa 10/8/2025 Process to update birth record;s geogrphic origin data. The "Genetic Ancestry" +** geographic_origin information must override the birth's geographic origin values. +** + +** +** +** +** +*/ + +CREATE Procedure onprc_ehr.p_BirthGeographicOriginUpdates + + as + + +BEGIN + + ----- Process data + + IF exists (select * From studydataset.c6d202_birth bir, studydataset.c6d512_geneticancestry b where bir.participantid = b.participantid + And b.enddate is null + and bir.qcstate = 18 + and b.qcstate = 18 + And bir.geographic_origin <> b.result + And b.result is not null + ) + + + + BEGIN + + ---- Update birth geographic origin + + Update bir + set bir.geographic_origin = b.result, + bir.modified = getdate(), + bir.modifiedby = b.modifiedby ---- ancestry staff + + From studydataset.c6d202_birth bir, studydataset.c6d512_geneticancestry b + where bir.participantid = b.participantid + And b.enddate is null + And bir.qcstate = 18 + And b.qcstate = 18 + And bir.geographic_origin <> b.result + And b.result is not null + + + If @@Error <> 0 + GoTo Err_Proc + +END ---- if + + + + + +RETURN 0 + + + Err_Proc: + -------Error Generated, process stopped + RETURN 1 + + +END + +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 deleted file mode 100644 index 5b69e6070..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-18.10-20.101.sql +++ /dev/null @@ -1,74 +0,0 @@ --- includes content of onprc_ehr-12.395-12.396.sql to onprc_ehr-17.704-17.705.sql from onprc19.1Prod --- removing all references to eIACUC processing - - - -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 deleted file mode 100644 index efb94f791..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.101-20.102.sql +++ /dev/null @@ -1,50 +0,0 @@ - /* 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 deleted file mode 100644 index 719f1c4fe..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.102-20.103.sql +++ /dev/null @@ -1,26 +0,0 @@ -/* 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 deleted file mode 100644 index eb1c5a1fd..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.103-20.104.sql +++ /dev/null @@ -1,32 +0,0 @@ - /* 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 deleted file mode 100644 index 818e499a4..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.104-20.105.sql +++ /dev/null @@ -1,41 +0,0 @@ -/* 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 deleted file mode 100644 index 851fcbebc..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.105-20.106.sql +++ /dev/null @@ -1,28 +0,0 @@ - /* 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 deleted file mode 100644 index b705a9d4d..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.106-20.107.sql +++ /dev/null @@ -1,62 +0,0 @@ - /* 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 deleted file mode 100644 index c4e832b59..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.411-20.412.sql +++ /dev/null @@ -1,85 +0,0 @@ -/****** 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 ******/ - -EXEC core.fn_dropifexists 'potentialDam_Source','onprc_ehr','TABLE'; -GO - -EXEC core.fn_dropifexists 'potentialsire_Source','onprc_ehr','TABLE'; -GO - -EXEC core.fn_dropifexists 'potentialParents_Source','onprc_ehr','TABLE'; -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 deleted file mode 100644 index 37a6236b7..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.412-20.413.sql +++ /dev/null @@ -1,68 +0,0 @@ - -/****** 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 - -GO 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 deleted file mode 100644 index 333ddd06e..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.413-20.414.sql +++ /dev/null @@ -1,67 +0,0 @@ - -/****** 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 - -GO 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 deleted file mode 100644 index d1581d44b..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.414-20.415.sql +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 deleted file mode 100644 index 9b3209e67..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.415-20.416.sql +++ /dev/null @@ -1,71 +0,0 @@ - -/****** 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 - -GO 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 deleted file mode 100644 index b75d1f9b7..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.416-20.417.sql +++ /dev/null @@ -1,20 +0,0 @@ -EXEC core.fn_dropifexists 'StudyDetails_Reference_Data','onprc_ehr','TABLE'; -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/dbscripts/sqlserver/onprc_ehr-20.904-20.905.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.904-20.905.sql deleted file mode 100644 index 07acfbe71..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.904-20.905.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE onprc_ehr.vet_assignment ADD project INT; diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.905-20.906.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.905-20.906.sql deleted file mode 100644 index 09310731a..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.905-20.906.sql +++ /dev/null @@ -1,144 +0,0 @@ -/****** Housing transfers alert project: By Kolli******/ -/* - Created 3 temp tables to get the list of NHP rooms usage. - The stored proc manages the addition and deleting data from the temp tables - at the time of execution via ETL process. - */ -EXEC core.fn_dropifexists 'availableCages_temp','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'availableCagesByRoom_temp','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'roomUtilization_temp','onprc_ehr','TABLE'; - -GO - --- Create the temp tables -CREATE TABLE [onprc_ehr].[availableCages_temp]( - [location] [varchar](50) NOT NULL, - [room] [varchar](200) NULL, - [cage] [varchar](200) NULL, - [row] [varchar](200) NULL, - [columnidx] [int] NULL, - [cage_type] [varchar](200) NULL, - [lowerCage] [varchar](200) NULL, - [lower_cage_type] [varchar](200) NULL, - [divider] [int] NULL, - [isAvailable] [int] NULL, - [isMarkedUnavailable] [int] NULL, - ) -; - -CREATE TABLE [onprc_ehr].[availableCagesByRoom_temp]( - [room] [varchar](200) NULL, - [availableCages] [int] NULL, - [markedUnavailable] [int] NULL - ) -; - -CREATE TABLE [onprc_ehr].[roomUtilization_temp]( - [room] [nvarchar](200) NULL, - [availableCages] [int] NULL, - [cagesUsed] [int] NULL, - [markedUnavailable] [int] NULL, - [cagesEmpty] [int] NULL, - [totalAnimals] [int] NULL - ) -; - -GO - - --- Create the stored proc here -/****** Object: StoredProcedure [onprc_ehr].[NHPRoomsUsage] ******/ - --- ============================================= --- Author: Lakshmi Kolli --- Create date: 3/6/2021 --- Description: Get the list of NHP rooms usage. The procedure is scheduled using a ETL process --- to list out the room utilization list at 4pm every day. The list is later used to check against for the --- empty rooms with the current list of rooms usage. --- ============================================= -CREATE PROCEDURE [onprc_ehr].[NHPRoomsUsage] - -AS -BEGIN - -----Truncate the temp table first -delete from onprc_ehr.availableCages_temp - -----Get the cages list and insert into the temp table -Insert Into onprc_ehr.availableCages_temp(location,room, cage, row, columnidx, cage_type, lowerCage, lower_cage_type, divider, isAvailable, isMarkedUnavailable) -SELECT - CASE - WHEN c.cage IS NULL THEN c.room - ELSE (c.room + '-' + c.cage) - END as location, - c.room, - c.cage, - (Select cp.row from ehr_lookups.cage_positions cp where c.cage = cp.cage) as row, - (Select cp.columnIdx from ehr_lookups.cage_positions cp where c.cage = cp.cage) as columnidx, - c.cage_type, - lc.cage as lowerCage, - lc.cage_type as lower_cage_type, - lc.divider, - --if the divider on the left-hand cage is separating, then these cages are separate - --and should be counted. if there's no left-hand cage, always include - CASE - WHEN c.cage_type = 'No Cage' THEN 0 - --WHEN lc.divider.countAsSeparate = 0 THEN false - WHEN (Select d.countAsSeparate from ehr_lookups.divider_types d where lc.divider = d.rowid) = 0 THEN 0 - ELSE 1 - END as isAvailable, - - CASE - WHEN (c.status IS NOT NULL AND c.status = 'Unavailable') then 1 - ELSE 0 - END as isMarkedUnavailable - -FROM ehr_lookups.cage c - --find the cage located to the left - LEFT JOIN ehr_lookups.cage lc ON (lc.cage_type != 'No Cage' and c.room = lc.room and (Select cp.row from ehr_lookups.cage_positions cp where c.cage = cp.cage) = (Select cp.row from ehr_lookups.cage_positions cp where lc.cage = cp.cage) and ((Select cp.columnIdx from ehr_lookups.cage_positions cp where c.cage = cp.cage) - 1) = (Select cp.columnIdx from ehr_lookups.cage_positions cp where lc.cage = cp.cage) ) ---WHERE c.room.housingType.value = 'Cage Location' - -----Truncate the temp table first -delete from onprc_ehr.availableCagesByRoom_temp - ---Get the available cages by room -Insert Into onprc_ehr.availableCagesByRoom_temp(room, availableCages, markedUnavailable) -SELECT - c.room, - count(*) as availableCages, - sum(c.isMarkedUnavailable) as markedUnavailable -FROM onprc_ehr.availableCages_temp c -WHERE c.isAvailable = 1 -GROUP BY c.room - -----Truncate the temp table first -delete from onprc_ehr.roomUtilization_temp - ---Get the rooms usage data -Insert Into onprc_ehr.roomUtilization_temp(room, availableCages, CagesUsed, MarkedUnavailable, CagesEmpty, TotalAnimals) -SELECT - r.room, - max(cbr.availableCages) as AvailableCages, - count(DISTINCT h.cage) as CagesUsed, - max(cbr.markedUnavailable) as MarkedUnavailable, - max(cbr.availableCages) - count(DISTINCT h.cage) - max(cbr.markedUnavailable) as CagesEmpty, - count(DISTINCT h.participantid) as TotalAnimals -FROM ehr_lookups.rooms r - LEFT JOIN ( - SELECT c.room, c.cage - FROM ehr_lookups.cage c - WHERE cage is not null - - --allow for rooms w/o cages - UNION ALL - SELECT r.room, null as cage - FROM ehr_lookups.rooms r - ) c on (r.room = c.room) - LEFT JOIN studyDataset.c6d194_housing h ON (r.room=h.room AND (c.cage=h.cage OR (c.cage is null and h.cage is null)) AND (((date <= GETDATE() AND enddate >= GETDATE()) OR (date <= GETDATE() AND enddate is null)))) - LEFT JOIN onprc_ehr.availableCagesByRoom_temp cbr ON (cbr.room = r.room) -WHERE r.datedisabled is null -GROUP BY r.room - -END - -GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.906-20.907.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.906-20.907.sql deleted file mode 100644 index 901e1937b..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.906-20.907.sql +++ /dev/null @@ -1,19 +0,0 @@ -EXEC core.fn_dropifexists 'PMIC_Reference_Data','onprc_ehr','TABLE'; - GO - -/****** Object: Table [onprc_ehr].[PMIC_Reference_Data] Script Date: 2/12/2020 ******/ -CREATE TABLE [onprc_ehr].[PMIC_Reference_Data]( - [RowId] INT IDENTITY(1,1)NOT NULL, - [value] [nvarchar](1000) NULL, - [name] [nvarchar](1000) NULL, - [remark] [nvarchar](4000) NULL, - [dateDisabled] [datetime] NULL, - [created] [datetime] NULL, - [createdBy] [int] NULL, - [modified] [datetime] NULL, - [modifiedBy] [int] NULL - - CONSTRAINT pk_PMIC_Reference_Data PRIMARY KEY (RowId) - ) - - GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.907-20.908.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.907-20.908.sql deleted file mode 100644 index 4cf1b33f2..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-20.907-20.908.sql +++ /dev/null @@ -1,5 +0,0 @@ -ALTER TABLE onprc_ehr.AvailableBloodVolume ALTER COLUMN Id nvarchar(32) NOT NULL; -GO - -ALTER TABLE onprc_ehr.AvailableBloodVolume ADD CONSTRAINT PK_AvailableBloodVolume PRIMARY KEY (Id); -GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.000-21.001.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.000-21.001.sql deleted file mode 100644 index 7606e5ff8..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.000-21.001.sql +++ /dev/null @@ -1,18 +0,0 @@ -EXEC core.fn_dropifexists 'ASB_SpecialInstructions','onprc_ehr','TABLE'; -GO - -/****** Object: Table [onprc_ehr].[ASB_SpecialInstructions] Script Date: 6/8/21 ******/ -CREATE TABLE [onprc_ehr].[ASB_SpecialInstructions]( - [RowId] INT IDENTITY(1,1)NOT NULL, - [value] [nvarchar](1000) NOT NULL, - [remarks] [nvarchar](2000) NULL, - [dateDisabled] [datetime] NULL, - [created] [datetime] NULL, - [createdBy] [int] NULL, - [modified] [datetime] NULL, - [modifiedBy] [int] NULL - - CONSTRAINT pk_ASB_SpecialInstructions PRIMARY KEY (RowId) - ) - - GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.001-21.002.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.001-21.002.sql deleted file mode 100644 index 02a165913..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.001-21.002.sql +++ /dev/null @@ -1,17 +0,0 @@ -EXEC core.fn_dropifexists 'ASB_SpecialInstructions','onprc_ehr','TABLE'; -GO - -/****** Object: Table [onprc_ehr].[ASB_SpecialInstructions] Script Date: 6/14/21 ******/ -CREATE TABLE [onprc_ehr].[ASB_SpecialInstructions]( - [value] [nvarchar](1000) NOT NULL, - [remarks] [nvarchar](2000) NULL, - [dateDisabled] [datetime] NULL, - [created] [datetime] NULL, - [createdBy] [int] NULL, - [modified] [datetime] NULL, - [modifiedBy] [int] NULL - - CONSTRAINT pk_ASB_SpecialInstructions PRIMARY KEY (value) - ) - - GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.002-21.003.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.002-21.003.sql deleted file mode 100644 index 8e84a59a1..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.002-21.003.sql +++ /dev/null @@ -1,379 +0,0 @@ - --- ======================================================================================================================================= --- Author: Lakshmi Kolli --- Create date: 2021-06-17 --- Description: Db tables creation for Prima reporting process. Created all the Prima tables in Prime onprc_ehr schema folder. --- ======================================================================================================================================= - ---Drop if exists (Labkey syntax) ---Tables -EXEC core.fn_dropifexists 'Prima_CaseBase','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_CassetteEvents','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_CassetteEventLocations','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_CassetteBases','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_LabstationTypes','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SlideBases','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SlideEvents','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SlideEventLocations','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_StainTests','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SurgicalWheels','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_UserPersons','onprc_ehr','TABLE'; ---Stored procs -EXEC core.fn_dropifexists 'PrimaSlideBillingReport', 'onprc_ehr', 'PROCEDURE'; -EXEC core.fn_dropifexists 'PrimaBlockBillingReport', 'onprc_ehr', 'PROCEDURE'; - -GO - ---Create tables ---1. UserPersons table -/****** Object: Table [onprc_ehr].[Prima_UserPersons] Script Date: 6/17/2021 3:52:21 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_UserPersons]( - [Id] [int] NOT NULL, - [DateOfBirth] [datetime] NULL, - [DepartmentName] [nvarchar](127) NULL, - [FirstName] [nvarchar](31) NULL, - [Gender] [tinyint] NOT NULL, - [LastName] [nvarchar](31) NULL, - [MiddleName] [nvarchar](31) NULL, - [Prefix] [int] NULL, - [SSN] [nvarchar](9) NULL, - [ProfessionalTitles] [nvarchar](127) NULL, - [DateOfDeath] [datetime] NULL - ) -; - ---2. SurgicalWheel table -/****** Object: Table [onprc_ehr].[Prima_SurgicalWheels] Script Date: 6/17/2021 3:53:24 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_SurgicalWheels]( - [Id] [int] IDENTITY(1,1) NOT NULL, - [Constant] [tinyint] NULL, - [Description] [nvarchar](255) NULL, - [IsActive] [bit] NOT NULL, - [CreatedByUserId] [int] NOT NULL, - [Deleted] [datetimeoffset](7) NULL, - [DeletedByUserId] [int] NULL, - [NextVersionId] [int] NULL, - [PreviousVersionId] [int] NULL, - [Title] [nvarchar](5) NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [LastModified] varchar(500) NOT NULL - ) -; - ---3. StainTests table -/****** Object: Table [onprc_ehr].[Prima_StainTests] Script Date: 6/17/2021 4:03:39 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_StainTests]( - [Id] [int] IDENTITY(1,1) NOT NULL, - [Abbreviation] [nvarchar](127) NOT NULL, - [Constant] [tinyint] NULL, - [CptCode] [nvarchar](6) NULL, - [Description] [nvarchar](255) NULL, - [StainTestCategoryId] [int] NOT NULL, - [TimeLength] [int] NOT NULL, - [CreatedByUserId] [int] NOT NULL, - [Deleted] [datetimeoffset](7) NULL, - [DeletedByUserId] [int] NULL, - [NextVersionId] [int] NULL, - [PreviousVersionId] [int] NULL, - [Title] [nvarchar](127) NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [LastModified] varchar(500) NOT NULL, - [IsValidated] [bit] NOT NULL - ) -; - ---4. Slidebases table -/****** Object: Table [onprc_ehr].[Prima_SlideBases] Script Date: 6/17/2021 4:04:46 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_SlideBases]( - [Id] [bigint] IDENTITY(1,1) NOT NULL, - [HandStain] [bit] NOT NULL, - [IsCharged] [bit] NOT NULL, - [StainTestId] [int] NOT NULL, - [DilutionFactor] [int] NULL, - [CaseBaseId] [int] NOT NULL, - [IsRadioActive] [bit] NOT NULL, - [PriorityLevelId] [int] NOT NULL, - [QcStatus] [tinyint] NOT NULL, - [SurgicalSerialPart] [smallint] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [OrderedStatus] [tinyint] NOT NULL, - [SavedIdentifier] [nvarchar](24) NULL, - [BarcodeContent] [nvarchar](72) NULL, - [CurrentBatchId] [int] NULL, - [AlternateIdentifier] [nvarchar](63) NULL, - [PrintStatus] [tinyint] NOT NULL, - [ItemStatus] [smallint] NOT NULL, - [FreeTextNotes] [nvarchar](4000) NULL - ) -; - ---5. CaseBase table -/****** Object: Table [onprc_ehr].[Prima_CaseBase] Script Date: 6/17/2021 4:07:39 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_CaseBase]( - [Id] [int] IDENTITY(1,1) NOT NULL, - [DifferentialDiagnosisId] [int] NULL, - [PathologistId] [int] NULL, - [PriorityLevelId] [int] NOT NULL, - [ResidentPathologistId] [int] NULL, - [SerialNumber] [int] NOT NULL, - [SurgeryDate] [datetime] NULL, - [SurgicalWheelId] [int] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [ResearcherId] [int] NULL, - [StudyId] [int] NULL, - [Discriminator] [nvarchar](128) NULL, - [StudyPhaseId] [int] NULL, - [CohortId] [int] NULL, - [SavedIdentifier] [nvarchar](max) NULL, - [Status] [tinyint] NOT NULL, - [AlternateIdentifier] [nvarchar](24) NULL - ) -; - ---6. CassetteEvents table -/****** Object: Table [onprc_ehr].[Prima_CassetteEvents] Script Date: 6/17/2021 4:08:57 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_CassetteEvents]( - [Id] [bigint] IDENTITY(1,1) NOT NULL, - [CassetteBaseId] [bigint] NOT NULL, - [EventType] [tinyint] NOT NULL, - [Status] [smallint] NOT NULL, - [Trigger] [tinyint] NOT NULL, - [UserId] [int] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [EventAction] [int] NULL, - [TissueProcessorId] [int] NULL, - [TissueProcessorProgramId] [int] NULL, - [Discriminator] [nvarchar](128) NOT NULL, - [CassetteBatchId] [int] NULL, - [CassetteOrderId] [bigint] NULL, - [AutomatedCassetteArchivalMachineId] [int] NULL, - [DisposalReasonId] [int] NULL, - [ShipmentId] [int] NULL, - [IsEstimated] [bit] NULL, - [PrintCount] [int] NULL, - [BarcodeContent] [nvarchar](max) NULL - ) -; - ---7. CassetteEventLocations table -/****** Object: Table [onprc_ehr].[Prima_CassetteEventLocations] Script Date: 6/17/2021 4:09:55 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_CassetteEventLocations]( - [CassetteEventId] [bigint] NOT NULL, - [LabStationTypeId] [int] NOT NULL, - [LocationId] [int] NOT NULL, - [WorkstationId] [int] NULL, - [Created] [datetimeoffset](7) NOT NULL, - [PersonId] [int] NULL - ) -; - ---8. CassetteBases table -/****** Object: Table [onprc_ehr].[Prima_CassetteBases] Script Date: 6/17/2021 4:10:42 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_CassetteBases]( - [Id] [bigint] IDENTITY(1,1) NOT NULL, - [CassetteColorId] [int] NOT NULL, - [EmbeddingInstructionId] [int] NOT NULL, - [EmbeddingNotes] [nvarchar](4000) NULL, - [HasTissue] [bit] NOT NULL, - [ProtocolCassetteId] [int] NULL, - [SpecimenBaseId] [bigint] NOT NULL, - [TissueCollectionId] [int] NULL, - [TissueProcessorProgramId] [int] NULL, - [TissueQuantity] [smallint] NOT NULL, - [CaseBaseId] [int] NOT NULL, - [IsRadioActive] [bit] NOT NULL, - [PriorityLevelId] [int] NOT NULL, - [QcStatus] [tinyint] NOT NULL, - [SurgicalSerialPart] [smallint] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [OrderedStatus] [tinyint] NOT NULL, - [SavedIdentifier] [nvarchar](24) NULL, - [BarcodeContent] [nvarchar](72) NULL, - [CurrentBatchId] [int] NULL, - [AlternateIdentifier] [nvarchar](63) NULL, - [PrintStatus] [tinyint] NOT NULL, - [ItemStatus] [smallint] NOT NULL - ) -; - ---9. LabstationTypes table -/****** Object: Table [onprc_ehr].[Prima_LabstationTypes] Script Date: 6/17/2021 4:41:00 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_LabstationTypes]( - [Id] [int] IDENTITY(1,1) NOT NULL, - [CanProcess] [int] NOT NULL, - [Constant] [int] NULL, - [Description] [nvarchar](255) NULL, - [IsEnabled] [bit] NOT NULL, - [Order] [int] NOT NULL, - [Title] [nvarchar](127) NULL, - [Created] [datetimeoffset](7) NOT NULL, - [LastModified] varchar(500) NOT NULL - ) -; - ---10. SlideEvents table -/****** Object: Table [onprc_ehr].[Prima_SlideEvents] Script Date: 6/17/2021 4:42:08 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_SlideEvents]( - [Id] [bigint] IDENTITY(1,1) NOT NULL, - [SlideBaseId] [bigint] NOT NULL, - [EventType] [tinyint] NOT NULL, - [Status] [smallint] NOT NULL, - [Trigger] [tinyint] NOT NULL, - [UserId] [int] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [EventAction] [int] NULL, - [CoverSlipperId] [int] NULL, - [OvenId] [int] NULL, - [OvenProgramId] [int] NULL, - [SlideImagerId] [int] NULL, - [SlideStainerId] [int] NULL, - [Discriminator] [nvarchar](128) NOT NULL, - [SlideBatchId] [int] NULL, - [SlideOrderId] [bigint] NULL, - [DisposalReasonId] [int] NULL, - [ShipmentId] [int] NULL, - [PrintCount] [int] NULL, - [BarcodeContent] [nvarchar](max) NULL, - [EquipmentId] [int] NULL, - [AutomatedSlideArchivalMachineId] [int] NULL - ) -; - ---11. SlideEventsLocations table -/****** Object: Table [onprc].[Prima_SlideEventLocations] Script Date: 6/17/2021 4:43:57 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_SlideEventLocations]( - [SlideEventId] [bigint] NOT NULL, - [LabStationTypeId] [int] NOT NULL, - [LocationId] [int] NOT NULL, - [WorkstationId] [int] NULL, - [Created] [datetimeoffset](7) NOT NULL, - [PersonId] [int] NULL - ) -; - -GO - ---Create the stored procedures for the SSRS reports --- ======================================================================================================================================= --- Author: Lakshmi Kolli --- Create date: 2021-06-15 --- Description: This stored procedure creates the Prima Slide billing report for the specified date range. --- This proc is used to create the SSRS report. --- ======================================================================================================================================= - -Create Procedure [onprc_ehr].[PrimaSlideBillingReport] - @startDate smalldatetime, - @endDate smalldatetime - -AS - -DECLARE -@staining int, -@embedding int, -@complete int - -BEGIN - --SET @startDate = '2000-01-01' -- 00:00:00.0000000 -07:00' - --SET @endDate = '2021-05-31' -- 00:00:00.0000000 -07:00' -SET @staining = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 10) -SET @embedding = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 7) -SET @complete = 7 SELECT Prima_surgicalwheels.title AS 'Surgical Wheel', - CASE - WHEN Prima_userpersons.lastname IS NOT NULL THEN - Concat(Prima_userpersons.lastname, ', ', Prima_userpersons.firstname, ' ', - Prima_userpersons.middlename) - ELSE 'Unassigned Pathologist' -END AS 'Pathologist', - Prima_staintests.title AS 'Stain Test', - sub2.slidecount AS 'Slide Count' - FROM (SELECT surgicalwheelid, - Prima_slidebases.staintestid, - Prima_casebase.pathologistid, - Count(*) AS SlideCount - FROM (SELECT Min(Prima_slideevents.created) AS VerifyOrBarcodeEventTime, - slidebaseid - FROM Prima_slideevents JOIN Prima_SlideEventLocations - ON Prima_slideeventlocations.SlideEventId = Prima_slideevents.id - AND Prima_slideeventlocations.LabStationTypeId = @staining WHERE eventtype = @complete - GROUP BY slidebaseid) sub - JOIN Prima_slidebases - ON slidebaseid = Prima_slidebases.id - JOIN Prima_casebase - ON Prima_casebase.id = Prima_slidebases.casebaseid WHERE sub.verifyorbarcodeeventtime >= @startDate - AND sub.verifyorbarcodeeventtime < @endDate - GROUP BY surgicalwheelid, - pathologistid, - staintestid) sub2 - LEFT JOIN Prima_userpersons - ON Prima_userpersons.id = sub2.pathologistid - LEFT JOIN Prima_surgicalwheels - ON Prima_surgicalwheels.id = sub2.surgicalwheelid - LEFT JOIN Prima_staintests - ON Prima_staintests.id = sub2.staintestid - ORDER BY 'Surgical Wheel', - 'Pathologist', - 'Stain Test' -END - -GO - --- ======================================================================================================================================= --- Author: Lakshmi Kolli --- Create date: 2021-06-15 --- Description: This stored procedure creates the Prima Block billing report for the specified date range. --- This proc is used to create the SSRS report. --- ======================================================================================================================================= - -CREATE Procedure [onprc_ehr].[PrimaBlockBillingReport] - @startDate smalldatetime, - @endDate smalldatetime - -AS - -DECLARE -@staining int, -@embedding int, -@complete int - -BEGIN - --SET @startDate = '2000-01-01' -- 00:00:00.0000000 -07:00' - --SET @endDate = '2021-05-31' -- 00:00:00.0000000 -07:00' -SET @staining = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 10) -SET @embedding = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 7) -SET @complete = 7 - -SELECT Prima_surgicalwheels.title AS 'Surgical Wheel', - CASE - WHEN Prima_userpersons.lastname IS NOT NULL THEN - Concat(Prima_userpersons.lastname, ', ', Prima_userpersons.firstname, ' ', - Prima_userpersons.middlename) - ELSE 'Unassigned Pathologist' - END AS 'Pathologist', - sub2.cassettecount AS 'Cassette Count' -FROM (SELECT surgicalwheelid, - Prima_casebase.pathologistid, - Count(*) AS CassetteCount - FROM (SELECT Min(Prima_cassetteevents.created) AS VerifyOrBarcodeEventTime, - cassettebaseid - FROM Prima_cassetteevents - JOIN Prima_CassetteEventLocations - ON Prima_CassetteEventLocations.CassetteEventId = Prima_cassetteevents.id - AND Prima_CassetteEventLocations.LabStationTypeId = @embedding WHERE eventtype = @complete - GROUP BY cassettebaseid) sub - JOIN Prima_cassettebases - ON cassettebaseid = Prima_cassettebases.id - JOIN Prima_casebase - ON Prima_casebase.id = Prima_cassettebases.casebaseid - WHERE sub.verifyorbarcodeeventtime >= @startDate - AND sub.verifyorbarcodeeventtime < @endDate - GROUP BY surgicalwheelid, - pathologistid) sub2 - LEFT JOIN Prima_userpersons - ON Prima_userpersons.id = sub2.pathologistid - LEFT JOIN Prima_surgicalwheels - ON Prima_surgicalwheels.id = sub2.surgicalwheelid - ORDER BY 'Surgical Wheel', - 'Pathologist' -END - -GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.003-21.004.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.003-21.004.sql deleted file mode 100644 index a0d2f4069..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.003-21.004.sql +++ /dev/null @@ -1,379 +0,0 @@ - --- ======================================================================================================================================= --- Author: Lakshmi Kolli --- Create date: 2021-06-17 --- Description: Db tables creation for Prima reporting process. Created all the Prima tables in Prime onprc_ehr schema folder. --- ======================================================================================================================================= - ---Drop if exists (Labkey syntax) ---Tables -EXEC core.fn_dropifexists 'Prima_CaseBase','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_CassetteEvents','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_CassetteEventLocations','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_CassetteBases','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_LabstationTypes','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SlideBases','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SlideEvents','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SlideEventLocations','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_StainTests','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SurgicalWheels','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_UserPersons','onprc_ehr','TABLE'; ---Stored procs -EXEC core.fn_dropifexists 'PrimaSlideBillingReport', 'onprc_ehr', 'PROCEDURE'; -EXEC core.fn_dropifexists 'PrimaBlockBillingReport', 'onprc_ehr', 'PROCEDURE'; - -GO - ---Create tables ---1. UserPersons table -/****** Object: Table [onprc_ehr].[Prima_UserPersons] Script Date: 6/17/2021 3:52:21 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_UserPersons]( - [Id] [int] NOT NULL, - [DateOfBirth] [datetime] NULL, - [DepartmentName] [nvarchar](127) NULL, - [FirstName] [nvarchar](31) NULL, - [Gender] [tinyint] NOT NULL, - [LastName] [nvarchar](31) NULL, - [MiddleName] [nvarchar](31) NULL, - [Prefix] [int] NULL, - [SSN] [nvarchar](9) NULL, - [ProfessionalTitles] [nvarchar](127) NULL, - [DateOfDeath] [datetime] NULL - ) -; - ---2. SurgicalWheel table -/****** Object: Table [onprc_ehr].[Prima_SurgicalWheels] Script Date: 6/17/2021 3:53:24 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_SurgicalWheels]( - [Id] [int] IDENTITY(1,1) NOT NULL, - [Constant] [tinyint] NULL, - [Description] [nvarchar](255) NULL, - [IsActive] [bit] NOT NULL, - [CreatedByUserId] [int] NOT NULL, - [Deleted] [datetimeoffset](7) NULL, - [DeletedByUserId] [int] NULL, - [NextVersionId] [int] NULL, - [PreviousVersionId] [int] NULL, - [Title] [nvarchar](5) NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [LastModified] [timestamp] NOT NULL - ) -; - ---3. StainTests table -/****** Object: Table [onprc_ehr].[Prima_StainTests] Script Date: 6/17/2021 4:03:39 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_StainTests]( - [Id] [int] IDENTITY(1,1) NOT NULL, - [Abbreviation] [nvarchar](127) NOT NULL, - [Constant] [tinyint] NULL, - [CptCode] [nvarchar](6) NULL, - [Description] [nvarchar](255) NULL, - [StainTestCategoryId] [int] NOT NULL, - [TimeLength] [int] NOT NULL, - [CreatedByUserId] [int] NOT NULL, - [Deleted] [datetimeoffset](7) NULL, - [DeletedByUserId] [int] NULL, - [NextVersionId] [int] NULL, - [PreviousVersionId] [int] NULL, - [Title] [nvarchar](127) NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [LastModified] [timestamp] NOT NULL, - [IsValidated] [bit] NOT NULL - ) -; - ---4. Slidebases table -/****** Object: Table [onprc_ehr].[Prima_SlideBases] Script Date: 6/17/2021 4:04:46 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_SlideBases]( - [Id] [bigint] IDENTITY(1,1) NOT NULL, - [HandStain] [bit] NOT NULL, - [IsCharged] [bit] NOT NULL, - [StainTestId] [int] NOT NULL, - [DilutionFactor] [int] NULL, - [CaseBaseId] [int] NOT NULL, - [IsRadioActive] [bit] NOT NULL, - [PriorityLevelId] [int] NOT NULL, - [QcStatus] [tinyint] NOT NULL, - [SurgicalSerialPart] [smallint] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [OrderedStatus] [tinyint] NOT NULL, - [SavedIdentifier] [nvarchar](24) NULL, - [BarcodeContent] [nvarchar](72) NULL, - [CurrentBatchId] [int] NULL, - [AlternateIdentifier] [nvarchar](63) NULL, - [PrintStatus] [tinyint] NOT NULL, - [ItemStatus] [smallint] NOT NULL, - [FreeTextNotes] [nvarchar](4000) NULL - ) -; - ---5. CaseBase table -/****** Object: Table [onprc_ehr].[Prima_CaseBase] Script Date: 6/17/2021 4:07:39 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_CaseBase]( - [Id] [int] IDENTITY(1,1) NOT NULL, - [DifferentialDiagnosisId] [int] NULL, - [PathologistId] [int] NULL, - [PriorityLevelId] [int] NOT NULL, - [ResidentPathologistId] [int] NULL, - [SerialNumber] [int] NOT NULL, - [SurgeryDate] [datetime] NULL, - [SurgicalWheelId] [int] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [ResearcherId] [int] NULL, - [StudyId] [int] NULL, - [Discriminator] [nvarchar](128) NULL, - [StudyPhaseId] [int] NULL, - [CohortId] [int] NULL, - [SavedIdentifier] [nvarchar](max) NULL, - [Status] [tinyint] NOT NULL, - [AlternateIdentifier] [nvarchar](24) NULL - ) -; - ---6. CassetteEvents table -/****** Object: Table [onprc_ehr].[Prima_CassetteEvents] Script Date: 6/17/2021 4:08:57 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_CassetteEvents]( - [Id] [bigint] IDENTITY(1,1) NOT NULL, - [CassetteBaseId] [bigint] NOT NULL, - [EventType] [tinyint] NOT NULL, - [Status] [smallint] NOT NULL, - [Trigger] [tinyint] NOT NULL, - [UserId] [int] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [EventAction] [int] NULL, - [TissueProcessorId] [int] NULL, - [TissueProcessorProgramId] [int] NULL, - [Discriminator] [nvarchar](128) NOT NULL, - [CassetteBatchId] [int] NULL, - [CassetteOrderId] [bigint] NULL, - [AutomatedCassetteArchivalMachineId] [int] NULL, - [DisposalReasonId] [int] NULL, - [ShipmentId] [int] NULL, - [IsEstimated] [bit] NULL, - [PrintCount] [int] NULL, - [BarcodeContent] [nvarchar](max) NULL - ) -; - ---7. CassetteEventLocations table -/****** Object: Table [onprc_ehr].[Prima_CassetteEventLocations] Script Date: 6/17/2021 4:09:55 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_CassetteEventLocations]( - [CassetteEventId] [bigint] NOT NULL, - [LabStationTypeId] [int] NOT NULL, - [LocationId] [int] NOT NULL, - [WorkstationId] [int] NULL, - [Created] [datetimeoffset](7) NOT NULL, - [PersonId] [int] NULL - ) -; - ---8. CassetteBases table -/****** Object: Table [onprc_ehr].[Prima_CassetteBases] Script Date: 6/17/2021 4:10:42 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_CassetteBases]( - [Id] [bigint] IDENTITY(1,1) NOT NULL, - [CassetteColorId] [int] NOT NULL, - [EmbeddingInstructionId] [int] NOT NULL, - [EmbeddingNotes] [nvarchar](4000) NULL, - [HasTissue] [bit] NOT NULL, - [ProtocolCassetteId] [int] NULL, - [SpecimenBaseId] [bigint] NOT NULL, - [TissueCollectionId] [int] NULL, - [TissueProcessorProgramId] [int] NULL, - [TissueQuantity] [smallint] NOT NULL, - [CaseBaseId] [int] NOT NULL, - [IsRadioActive] [bit] NOT NULL, - [PriorityLevelId] [int] NOT NULL, - [QcStatus] [tinyint] NOT NULL, - [SurgicalSerialPart] [smallint] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [OrderedStatus] [tinyint] NOT NULL, - [SavedIdentifier] [nvarchar](24) NULL, - [BarcodeContent] [nvarchar](72) NULL, - [CurrentBatchId] [int] NULL, - [AlternateIdentifier] [nvarchar](63) NULL, - [PrintStatus] [tinyint] NOT NULL, - [ItemStatus] [smallint] NOT NULL - ) -; - ---9. LabstationTypes table -/****** Object: Table [onprc_ehr].[Prima_LabstationTypes] Script Date: 6/17/2021 4:41:00 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_LabstationTypes]( - [Id] [int] IDENTITY(1,1) NOT NULL, - [CanProcess] [int] NOT NULL, - [Constant] [int] NULL, - [Description] [nvarchar](255) NULL, - [IsEnabled] [bit] NOT NULL, - [Order] [int] NOT NULL, - [Title] [nvarchar](127) NULL, - [Created] [datetimeoffset](7) NOT NULL, - [LastModified] [timestamp] NOT NULL - ) -; - ---10. SlideEvents table -/****** Object: Table [onprc_ehr].[Prima_SlideEvents] Script Date: 6/17/2021 4:42:08 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_SlideEvents]( - [Id] [bigint] IDENTITY(1,1) NOT NULL, - [SlideBaseId] [bigint] NOT NULL, - [EventType] [tinyint] NOT NULL, - [Status] [smallint] NOT NULL, - [Trigger] [tinyint] NOT NULL, - [UserId] [int] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [EventAction] [int] NULL, - [CoverSlipperId] [int] NULL, - [OvenId] [int] NULL, - [OvenProgramId] [int] NULL, - [SlideImagerId] [int] NULL, - [SlideStainerId] [int] NULL, - [Discriminator] [nvarchar](128) NOT NULL, - [SlideBatchId] [int] NULL, - [SlideOrderId] [bigint] NULL, - [DisposalReasonId] [int] NULL, - [ShipmentId] [int] NULL, - [PrintCount] [int] NULL, - [BarcodeContent] [nvarchar](max) NULL, - [EquipmentId] [int] NULL, - [AutomatedSlideArchivalMachineId] [int] NULL - ) -; - ---11. SlideEventsLocations table -/****** Object: Table [onprc].[Prima_SlideEventLocations] Script Date: 6/17/2021 4:43:57 PM ******/ -CREATE TABLE [onprc_ehr].[Prima_SlideEventLocations]( - [SlideEventId] [bigint] NOT NULL, - [LabStationTypeId] [int] NOT NULL, - [LocationId] [int] NOT NULL, - [WorkstationId] [int] NULL, - [Created] [datetimeoffset](7) NOT NULL, - [PersonId] [int] NULL - ) -; - -GO - ---Create the stored procedures for the SSRS reports --- ======================================================================================================================================= --- Author: Lakshmi Kolli --- Create date: 2021-06-15 --- Description: This stored procedure creates the Prima Slide billing report for the specified date range. --- This proc is used to create the SSRS report. --- ======================================================================================================================================= - -Create Procedure [onprc_ehr].[PrimaSlideBillingReport] - @startDate smalldatetime, - @endDate smalldatetime - -AS - -DECLARE -@staining int, -@embedding int, -@complete int - -BEGIN - --SET @startDate = '2000-01-01' -- 00:00:00.0000000 -07:00' - --SET @endDate = '2021-05-31' -- 00:00:00.0000000 -07:00' -SET @staining = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 10) -SET @embedding = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 7) -SET @complete = 7 SELECT Prima_surgicalwheels.title AS 'Surgical Wheel', - CASE - WHEN Prima_userpersons.lastname IS NOT NULL THEN - Concat(Prima_userpersons.lastname, ', ', Prima_userpersons.firstname, ' ', - Prima_userpersons.middlename) - ELSE 'Unassigned Pathologist' -END AS 'Pathologist', - Prima_staintests.title AS 'Stain Test', - sub2.slidecount AS 'Slide Count' - FROM (SELECT surgicalwheelid, - Prima_slidebases.staintestid, - Prima_casebase.pathologistid, - Count(*) AS SlideCount - FROM (SELECT Min(Prima_slideevents.created) AS VerifyOrBarcodeEventTime, - slidebaseid - FROM Prima_slideevents JOIN Prima_SlideEventLocations - ON Prima_slideeventlocations.SlideEventId = Prima_slideevents.id - AND Prima_slideeventlocations.LabStationTypeId = @staining WHERE eventtype = @complete - GROUP BY slidebaseid) sub - JOIN Prima_slidebases - ON slidebaseid = Prima_slidebases.id - JOIN Prima_casebase - ON Prima_casebase.id = Prima_slidebases.casebaseid WHERE sub.verifyorbarcodeeventtime >= @startDate - AND sub.verifyorbarcodeeventtime < @endDate - GROUP BY surgicalwheelid, - pathologistid, - staintestid) sub2 - LEFT JOIN Prima_userpersons - ON Prima_userpersons.id = sub2.pathologistid - LEFT JOIN Prima_surgicalwheels - ON Prima_surgicalwheels.id = sub2.surgicalwheelid - LEFT JOIN Prima_staintests - ON Prima_staintests.id = sub2.staintestid - ORDER BY 'Surgical Wheel', - 'Pathologist', - 'Stain Test' -END - - GO - --- ======================================================================================================================================= --- Author: Lakshmi Kolli --- Create date: 2021-06-15 --- Description: This stored procedure creates the Prima Block billing report for the specified date range. --- This proc is used to create the SSRS report. --- ======================================================================================================================================= - -CREATE Procedure [onprc_ehr].[PrimaBlockBillingReport] - @startDate smalldatetime, - @endDate smalldatetime - -AS - -DECLARE -@staining int, -@embedding int, -@complete int - -BEGIN - --SET @startDate = '2000-01-01' -- 00:00:00.0000000 -07:00' - --SET @endDate = '2021-05-31' -- 00:00:00.0000000 -07:00' -SET @staining = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 10) -SET @embedding = (SELECT id FROM Prima_LabstationTypes WHERE Constant = 7) -SET @complete = 7 - -SELECT Prima_surgicalwheels.title AS 'Surgical Wheel', - CASE - WHEN Prima_userpersons.lastname IS NOT NULL THEN - Concat(Prima_userpersons.lastname, ', ', Prima_userpersons.firstname, ' ', - Prima_userpersons.middlename) - ELSE 'Unassigned Pathologist' - END AS 'Pathologist', - sub2.cassettecount AS 'Cassette Count' -FROM (SELECT surgicalwheelid, - Prima_casebase.pathologistid, - Count(*) AS CassetteCount - FROM (SELECT Min(Prima_cassetteevents.created) AS VerifyOrBarcodeEventTime, - cassettebaseid - FROM Prima_cassetteevents - JOIN Prima_CassetteEventLocations - ON Prima_CassetteEventLocations.CassetteEventId = Prima_cassetteevents.id - AND Prima_CassetteEventLocations.LabStationTypeId = @embedding WHERE eventtype = @complete - GROUP BY cassettebaseid) sub - JOIN Prima_cassettebases - ON cassettebaseid = Prima_cassettebases.id - JOIN Prima_casebase - ON Prima_casebase.id = Prima_cassettebases.casebaseid - WHERE sub.verifyorbarcodeeventtime >= @startDate - AND sub.verifyorbarcodeeventtime < @endDate - GROUP BY surgicalwheelid, - pathologistid) sub2 - LEFT JOIN Prima_userpersons - ON Prima_userpersons.id = sub2.pathologistid - LEFT JOIN Prima_surgicalwheels - ON Prima_surgicalwheels.id = sub2.surgicalwheelid -ORDER BY 'Surgical Wheel', - 'Pathologist' -END - - GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.100-21.101.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.100-21.101.sql deleted file mode 100644 index 02a165913..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.100-21.101.sql +++ /dev/null @@ -1,17 +0,0 @@ -EXEC core.fn_dropifexists 'ASB_SpecialInstructions','onprc_ehr','TABLE'; -GO - -/****** Object: Table [onprc_ehr].[ASB_SpecialInstructions] Script Date: 6/14/21 ******/ -CREATE TABLE [onprc_ehr].[ASB_SpecialInstructions]( - [value] [nvarchar](1000) NOT NULL, - [remarks] [nvarchar](2000) NULL, - [dateDisabled] [datetime] NULL, - [created] [datetime] NULL, - [createdBy] [int] NULL, - [modified] [datetime] NULL, - [modifiedBy] [int] NULL - - CONSTRAINT pk_ASB_SpecialInstructions PRIMARY KEY (value) - ) - - GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.200-21.201.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.200-21.201.sql deleted file mode 100644 index f63189d9b..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.200-21.201.sql +++ /dev/null @@ -1,39 +0,0 @@ -EXEC core.fn_dropifexists 'StudyDetails_RandalData','onprc_ehr','TABLE'; -GO - -/****** Object: Table [onprc_ehr].[StudyDetails_RandalData] Script Date: 10/13/2021 -Purpose Target for import from external datasource mfsh -******/ - -CREATE TABLE [onprc_ehr].[StudyDetails_RandalData]( - [id] INT NOT NULL, - [Rh] [nvarchar](100) NULL, - [Cohort] [nvarchar](1000) NULL, - [PI] [nvarchar](100) NULL, - [Cohort_id] INT NULL, - [subcohort] [nvarchar](100) NULL, - [grp] [nvarchar](100) NULL, - [grp_order] INT NULL, - [grp_id] INT NOT NULL, - [rhCode] [nvarchar](100) NULL, - [grpnm] INT NULL, - [Sex] [nvarchar](100) NULL, - [cohortStart] [date] null, - [cohortEnd] [date] null, - [Do] [date] null, - [DPC0] [date] null, - [contprog] [nvarchar](100) NULl, - [PIDO] date null, - [DPTO] date Null, - [Birth] date null, - [Nx_date] date null, - [stims] [nvarchar](100) NULl, - [active] [nvarchar](100) NULl - CONSTRAINT pk_StudyDetails_Randal PRIMARY KEY (Id) - ) - - - - - - GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.201-21.202.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.201-21.202.sql deleted file mode 100644 index de0c561c1..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-21.201-21.202.sql +++ /dev/null @@ -1,20 +0,0 @@ -EXEC core.fn_dropifexists 'BSUageclass','onprc_ehr','TABLE'; -GO - - -CREATE TABLE [onprc_ehr].[BSUageclass] -( - [rowId] INT IDENTITY(1,1)NOT NULL, - label varchar(255) NULL, - species varchar(255) NULL, - gender varchar(5) NULL, - ageclass INT NULL, - min [float] NULL, - max [float] NULL, - [sort_order] INT NULL, - [dateDisabled] [datetime] NULL, - - CONSTRAINT PK_bsuageclass PRIMARY KEY (rowId) - - ) - GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-22.000-22.001.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-22.000-22.001.sql deleted file mode 100644 index 2b577d8d9..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-22.000-22.001.sql +++ /dev/null @@ -1,4 +0,0 @@ --- This stored procedure was incorrectly named and placed in the wrong schema when created in onprc_ehr-18.10-20.101.sql. --- It's also unused, so just drop it. -IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND object_id = OBJECT_ID('[dbo].[onprc_ehr.etlStep1eIACUCtoPRIMEProcessing]')) - DROP PROCEDURE [dbo].[onprc_ehr.etlStep1eIACUCtoPRIMEProcessing] diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-22.001-22.002.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-22.001-22.002.sql deleted file mode 100644 index f1ffdca30..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-22.001-22.002.sql +++ /dev/null @@ -1,4 +0,0 @@ ---added to allow department descignation for R & L -EXEC core.fn_dropifexists 'Investigators', 'onprc_ehr', 'COLUMN', 'Department'; -GO -ALTER TABLE onprc_ehr.investigators ADD [Department] varchar(250) Null; diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.000-23.001.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.000-23.001.sql deleted file mode 100644 index 75f51ddf9..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.000-23.001.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE [onprc_ehr].[Epoc_tests] -( - rowid INT IDENTITY(1,1)NOT NULL, - testid nvarchar(500) NOT NULL, - name nvarchar(500) NULL, - units nvarchar(50) NULL, - alias nvarchar(200) NULL, - alertOnAbnormal [bit] NULL, - alertOnAny [bit] NULL, - includeInPanel [bit]NULL, - objectid ENTITYID NOT NULL, - sort_order [int] NULL, - container ENTITYID - - CONSTRAINT PK_EpocTestsObject PRIMARY KEY (objectid) - - ) - GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.001-23.002.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.001-23.002.sql deleted file mode 100644 index 3f78aad10..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.001-23.002.sql +++ /dev/null @@ -1,66 +0,0 @@ -CREATE TABLE onprc_ehr.Reference_Data_IDkey -( - rowId int identity(1,1), - displayName varchar(4000) DEFAULT NULL, - idkey integer NOT NULL, - columnName varchar(1000) NOT NULL, - status integer NULL, - type varchar(500) NULL, - sort_order integer null, - created datetime NOT NULL, - endDate datetime DEFAULT NULL - - - CONSTRAINT pk_referenceIDkey PRIMARY KEY (idkey) -) - - -GO - - --- Author: R. Blasa --- Created: 10-10-2022 --- Description: Stored procedure program to initially populate onprc_ehr.Reference_Data_IDkey. - - -Create Procedure [onprc_ehr].[p_PopulateReferenceDataIDkey] - - -AS - - -BEGIN - ---- Reset lookiup table - - truncate table onprc_ehr.Reference_Data_IDkey - - ----- Create initial entries - Insert into onprc_ehr.Reference_Data_IDkey - select - - Name, - UserId, - 'Active_Groups', - Active, - Type, - NULL as sort_order, ---- Sort_Order - GETDATE() as created, ----- Created - NULL as enddate ----- Date Disabled - - FROM core.Principals - where type = 'g' - and UserId > 0 - and Active = 1 - and Container is null - - If @@Error <> 0 - GoTo Err_Proc - - - Return 0 - -Err_Proc: Return 1 - -END - -GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.002-23.003.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.002-23.003.sql deleted file mode 100644 index 9739348d2..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.002-23.003.sql +++ /dev/null @@ -1,10 +0,0 @@ - --- Created: 10-10-2022 R. Blasa to correct type definitionss - - -ALTER TABLE onprc_ehr.encounter_summaries_remarks ALTER COLUMN createdby userid; -GO - - -ALTER TABLE onprc_ehr.encounter_summaries_remarks ALTER COLUMN modifiedby userid; -GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.003-23.004.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.003-23.004.sql deleted file mode 100644 index 86353a5de..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.003-23.004.sql +++ /dev/null @@ -1,155 +0,0 @@ - -CREATE TABLE [onprc_ehr].[PrimeProblemListTemp]( - [rowid] [int] IDENTITY(100,1) NOT NULL, - [animalid] [varchar](200) NULL, - [date] datetime NULL, - [objectid] [varchar](4000) NULL, - [caseid] [varchar](4000) NULL, - [case_enddate] datetime, - [created] datetime - - - ) - GO - - - --- Author: R. Blasa --- Created: 10-20-2022 --- Description: Stored procedure program assigns Clinical Cases ending dates to all Clinical Problem list that --- have no ending dates, and shares the same case ids - - -CREATE Procedure [onprc_ehr].[p_CaseToPRoblemListupdates] - - - - -AS - - - -DECLARE - @SearchKey Int, - @TempsearchKey Int, - @TempObjectID varchar(4000), - @TaskId varchar(4000), - @ObjectId varchar(4000), - @CaseEnddate datetime, - @SessionID Int - - - - -BEGIN - - - - ---- Reset temp table - -Truncate table onprc_ehr.PrimeProblemListTemp - - - If @@Error <> 0 - GoTo Err_Proc - - - - --- Generate a list of Problem List records to close ) - - Insert into onprc_ehr.PrimeProblemListTemp - - select - b.participantid, - b.date, - b.objectid, - b.caseid, - a.enddate ,------ case ending date - getdate() ------ date created - - - from studyDataset.c6d176_cases a, studyDataset.c6d200_problem b - where a.objectid = b.caseid - and a.category in ('clinical','Behavior') - and a.qcstate = 18 and b.qcstate = 18 - and b.enddate is null - and a.enddate is not null - and a.participantid = b.participantid - order by a.date desc - - - If @@Error <> 0 - GoTo Err_Proc - - - ---- Reset temp variables - -Set @SearchKey = 0 -Set @TempSearchKey = 0 -Set @TempObjectid = NULL -Set @CaseEnddate = NULL - ------ extract initial row id - -Select Top 1 @Searchkey = rowid from onprc_ehr.PrimeProblemListTemp -Order by rowid - - - While @TempSearchKey < @SearchKey - BEGIN - - -----Begin update process - - If exists (select * from onprc_ehr.PrimeProblemListTemp Where rowid = @SearchKey) - BEGIN - - Select @TempObjectid =objectid, @CaseEnddate = case_enddate from onprc_ehr.PrimeProblemListTemp - Where rowid = @Searchkey - - -------Begin record editing process - - Update prob - set prob.enddate = @CaseEnddate - From studyDataset.c6d200_problem prob - where prob.objectid = @TempObjectID - - - If @@Error <> 0 - GoTo Err_Proc - END - - - ----- Proceed and fetch the next record - - Set @TempSearchKey = @SearchKey - - Select Top 1 @SearchKey = rowid from onprc_ehr.PrimeProblemListTemp - Where rowid > @TempSearchKey - Order by rowid - - - END ---- While @TempSearchKey - - - ----- Create a master copy of the completed transaction - - Select * into onprc_ehr.PrimeProblemListMaster - from onprc_ehr.PrimeProblemListTemp - If @@Error <> 0 - GoTo Err_Proc - - - -No_Records: - - RETURN 0 - - -Err_Proc: - -------Error Generated, Transfer process stopped - RETURN 1 - - -END - -GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.004-23.005.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.004-23.005.sql deleted file mode 100644 index cc015cea0..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.004-23.005.sql +++ /dev/null @@ -1,12 +0,0 @@ ----Create 5-2023-08-15 jonesga - -EXEC core.fn_dropifexists 'PrimeProblemListTemp', 'onprc_ehr', 'TABLE', NULL; -GO - -EXEC core.fn_dropifexists 'PrimeProblemListMaster', 'onprc_ehr', 'TABLE', NULL; -GO - -EXEC core.fn_dropifexists 'p_CaseToPRoblemListupdates', 'onprc_ehr', 'PROCEDURE', NULL; -GO - - diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.005-23.006.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.005-23.006.sql deleted file mode 100644 index a7a15b24d..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.005-23.006.sql +++ /dev/null @@ -1,122 +0,0 @@ - - - - --- Author: R. Blasa --- Created: 8-30-2023 --- Description: Stored procedure program to allow cage status settings to be updated by default to "Normal". - - -CREATE Procedure [onprc_ehr].[p_CageStatusupdates] - -AS - -BEGIN - -If exists (select * from ehr_lookups.cage) - BEGIN - --- Set Cage status to Normal ) - - Update ehr_lookups.cage - Set status = 'Normal' - Where status is null - - - If @@Error <> 0 - GoTo Err_Proc - -END - - RETURN 0 - - -Err_Proc: - -------Error Generated - RETURN 1 - - -END - -GO - - --- Author: R. Blasa --- Created: 8-30-2023 --- Description: Temp table for cage information audit history. - -CREATE TABLE [onprc_ehr].[CageAuditLog]( - [searchid] [int] IDENTITY(100,1) NOT NULL, - [rowid] [int] NULL, - [location] [nvarchar](100) NULL, - [room] [varchar](200) NULL, - [cage] [varchar](200) NULL, - [divider] [int] NULL, - [cage_type] [varchar](100) NULL, - [hasTunnel] [bit] NULL, - [status] [varchar](200) NULL, - [Container] [dbo].[ENTITYID] NOT NULL, - [area] [varchar](500) NULL, - [housingtype] [varchar](500) NULL, - [housingcondition] [varchar](500) NULL, - [date_created] [smalldatetime] NULL - ) ON [PRIMARY] - - GO - - - - - - - - - - --- Author: R. Blasa --- Created: 8-30-2023 --- Description: Stored procedure program to provide historical cage information audit history. - - -CREATE Procedure [onprc_ehr].[p_CageAuditHistoryProcess] - -AS - - -BEGIN - - --- Create historical cage data -If exists (select * from onprc_ehr.CageAuditLog) -BEGIN -Insert into onprc_ehr.CageAuditLog -Select rowid, - a.location, - a.room, - a.cage, - a.divider, - a.cage_type, - a.hasTunnel, - a.status, - a.container, - (select h.area from ehr_lookups.rooms h where h.room = a.room) as area, - (select s.value from ehr_lookups.rooms h, ehr_lookups.lookups s where h.room = a.room and s.rowid = h.housingtype) as housingtype, - (select s.value from ehr_lookups.rooms h, ehr_lookups.lookups s where h.room = a.room and s.rowid = h.housingcondition) as housingcondition, - getdate() - -from ehr_lookups.cage a - - If @@Error <> 0 - GoTo Err_Proc - -END --- if exists - - RETURN 0 - - -Err_Proc: - -------Error Generated - RETURN 1 - - -END - -GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.006-23.007.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.006-23.007.sql deleted file mode 100644 index bdc14bb6f..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.006-23.007.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE onprc_ehr.CageAuditLog ADD CONSTRAINT pk_searchid PRIMARY KEY (searchid); \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.007-23.008.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.007-23.008.sql deleted file mode 100644 index 51cfae8b2..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.007-23.008.sql +++ /dev/null @@ -1,84 +0,0 @@ --- ================================================================================================= --- Add MPA Clinical remarks: By, Lakshmi Kolli --- Created on: 1/25/2024 -/* Description: Created 1 temp table to store the clinical remarks records. - The stored proc manages the addition and deleting clinical remarks data from the temp table - at the time of execution via ETL process. - */ --- ================================================================================================= - ---Drop table if exists -EXEC core.fn_dropifexists 'Temp_ClnRemarks','onprc_ehr','TABLE'; ---Drop Stored proc if exists -EXEC core.fn_dropifexists '[onprc_ehr].[MPA_ClnRemarkAddition]', 'onprc_ehr', 'PROCEDURE'; -GO - --- Create the temp table -CREATE TABLE onprc_ehr.Temp_ClnRemarks -( - date datetime, - qcstate int, - participantid nvarchar(32), - project int, - remark nvarchar(250) , - p nvarchar(250) , - performedby nvarchar(250) , - category nvarchar(250) , - taskid nvarchar(4000), - createdby int, - modifiedby int -) -; - -GO - --- Create the stored proc -/****** Object: StoredProcedure [onprc_ehr].[MPA_ClnRemarkAddition] Script Date: 1/25/2024 *****/ --- ================================================================================= - -- Author: Lakshmi Kolli - -- Create date: 1/25/2024 - -- Description: This procedure identifies if an animal received an MPA injection - -- and inserts a clinical remark into animal's record. --- ================================================================================= - -CREATE PROCEDURE [onprc_ehr].[MPA_ClnRemarkAddition] -AS - -DECLARE -@MPACount Int, - @taskId nvarchar(4000) - -BEGIN - --Delete all rows from the temp_Drug table - Delete From onprc_ehr.Temp_ClnRemarks - - --Check if the MPA injection E-85760 was administered today - Select @MPACount = COUNT(*) From studyDataset.c6d178_drug - Where code = 'E-85760' And CONVERT(DATE, date) = CONVERT(DATE, GETDATE()) And qcstate = 18 - - --Found entries, so, enter the clinical remarks now - If @MPACount > 0 - Begin - -- Create a Task entry in ehr.tasks table - Set @taskid = NEWID() -- creating taskid - Insert Into ehr.tasks - (taskid, category, title, formtype, qcstate, assignedto, duedate, createdby, created, - container, modifiedby, modified, description, datecompleted) - Values - (@taskid, 'Task', 'Bulk Clinical Entry', 'Bulk Clinical Entry', 18, 1003, GETDATE(), 1003, GETDATE(), - 'CD17027B-C55F-102F-9907-5107380A54BE', 1003, GETDATE(), 'Created by the ETL process', GETDATE()) - - --Insert the clinical remark into the temp clinical remarks table. - /* Get all the Animals who had MPA injection today from studyDataset.c6d178_drug - and INSERT the data into the studyDataset.c6d185_clinremarks table */ - Insert Into onprc_ehr.Temp_ClnRemarks ( - date, qcstate, participantid, project, remark, p, performedby, category, taskid, createdby, modifiedby - ) - Select GETDATE(), 18, participantid, project, 'Remark entered by the ETL process', 'MPA injection administered', 'onprcitsupport@ohsu.edu', 'Clinical', @taskId, 1003, 1003 - From studyDataset.c6d178_drug - Where code = 'E-85760' And CONVERT(DATE, date) = CONVERT(DATE, GETDATE()) And qcstate = 18 - End - -END - -GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.008-23.009.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.008-23.009.sql deleted file mode 100644 index 3c629cf64..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.008-23.009.sql +++ /dev/null @@ -1,13 +0,0 @@ -CREATE TABLE onprc_ehr.Environmental_Reference_Data ( - rowId int identity(1,1), - label varchar(250) DEFAULT NULL, - value varchar(500) , - columnName varchar(255) NOT NULL, - sort_order integer null, - endDate datetime DEFAULT NULL, - - CONSTRAINT pk_referenceenv PRIMARY KEY (value) -) - - - GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.009-23.010.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.009-23.010.sql deleted file mode 100644 index 709ebfc7d..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.009-23.010.sql +++ /dev/null @@ -1,35 +0,0 @@ -CREATE TABLE onprc_ehr.Environmental_Assessment( - rowid int IDENTITY(100,1) NOT NULL, - date datetime NULL, - service_requested varchar(300) NULL, - charge_unit varchar(300) NULL, - testing_location varchar(300) NULL, - test_type varchar(300) NULL, - test_results varchar(100) NULL, - pass_fail varchar(100) NULL, - biological_Cycle varchar(300) NULL, - biological_BI varchar(300) NULL, - action varchar(300) NULL, - performedby varchar(300) NULL, - remarks varchar(300) NULL, - water_source varchar(300) NULL, - surface_tested varchar(300) NULL, - retest varchar(300) NULL, - colony_count varchar(300) NULL, - test_method varchar(300) NULL, - objectid ENTITYID Not Null, - createdby int NULL, - created datetime NULL, - modifiedby int NULL, - modified datetime NULL, - Container ENTITYID NOT NULL, - taskid entityid, - qcstate int NULL, - formsort int NULL - - - CONSTRAINT PK_assessment PRIMARY KEY (objectid) -) - - GO - diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.010-23.011.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.010-23.011.sql deleted file mode 100644 index a96490843..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.010-23.011.sql +++ /dev/null @@ -1,1358 +0,0 @@ - - -/* -** -** Created by Date -** -** Blasa 4-5-2024 Process to update Environmental Assessment data set ldk file from Production database. -** -** -** -*/ - - -CREATE Procedure onprc_ehr.p_Environmental_Update_Process - - - - AS - - -BEGIN - - IF exists (Select * from [list].[c8754d723_surface_sanitation_minus_rodac_48hr]) -BEGIN - - -Insert into onprc_ehr.Environmental_Assessment - -(date, - testing_location, ----TestSite - service_requested, - test_type, ------TestType - colony_count, ---ColonyCount Before: test_resuls - pass_fail, -----PassFail - performedby, ------Collectedby - action, ----Action - remarks, ----comments - objectid, - created, - createdby, - modified, - modifiedby, - qcstate, - container) - -select date, - TestSite, - 'Sanitation: Contact Plate' , - TestType, - ColonyCount, - PassFail, - CollectedBy, - Action, - comment, - newid(), - getdate(), - 1896, - getdate(), - 1896, - 18, - '98F39B23-5E3B-1037-AFE5-BD25D057100A' -from [list].[c8754d723_surface_sanitation_minus_rodac_48hr] - - - - If @@Error <> 0 - GoTo Err_Proc -END ----- - - - - IF exists (Select * from [list].[c8754d726_h2o_testing]) -BEGIN - -Insert into onprc_ehr.Environmental_Assessment - -(date, - testing_location, ---testing Location - service_requested, - water_source, ----H2OSource, - test_type, ----- Testtype - test_results, ----result - pass_fail, ----PassFail - remarks, - objectid, - created, - createdby, - modified, - modifiedby, - qcstate, - container) - -select date, - TestSite, - 'Sanitation: Water Test', - H2OSource, - TestType, - result, - PassFail, - comment, - newid(), - getdate(), - 1896, - getdate(), - 1896, - 18, - '98F39B23-5E3B-1037-AFE5-BD25D057100A' -from [list].[c8754d726_h2o_testing] - - If @@Error <> 0 - GoTo Err_Proc -END ----- - - IF exists (Select * from list.c8754d795_biological_indicator_log) -BEGIN - -Insert into onprc_ehr.Environmental_Assessment - -(date, - testing_location, ---autoclave - service_requested, - biological_Cycle, ----cycle (if applicable) - biological_BI, ----BI# (for ASA) - pass_fail, ---Pass / Fail - retest , ----Results Read by Before: test_results - action, ----- action - performedby, ----collected by - remarks, - objectid, - created, - createdby, - modified, - modifiedby, - qcstate, - container) - -select date, - autoclave, - 'Sanitation: Bio-indicator', - [cycle (if applicable)], - [BI# (for ASA)], - [Pass / Fail], - [Results Read by], - action, - [Collected By], - comment, - newid(), - getdate(), - 1896, - getdate(), - 1896, - 18, - '98F39B23-5E3B-1037-AFE5-BD25D057100A' - -from list.c8754d795_biological_indicator_log - - If @@Error <> 0 - GoTo Err_Proc -END ----- - - - IF exists (Select * from list.c8754d731_atp_testing) -BEGIN - - ---- Note: ATP Testing is strictly Kati's entries only - - -Insert into onprc_ehr.Environmental_Assessment - -(date, - performedby, ---tech inititals - service_requested, - testing_location, ----Area - surface_tested, --- Surface column before -->biological_reader - pass_fail, --- initial - remarks, ---comments - retest, ----retest column before---->water_source - test_results, -------Lab/Group - action , -----location - objectid, - created, - createdby, - modified, - modifiedby, - qcstate, - container) - -select date, - Tech_Initials, - 'Sanitation: ATP', - area, - Surface, - initial, - comments, - retest, - Lab_Group, - location, - newid(), - getdate(), - 1896, - getdate(), - 1896, - 18, - '98F39B23-5E3B-1037-AFE5-BD25D057100A' -from list.c8754d731_atp_testing - - If @@Error <> 0 - GoTo Err_Proc -END ----- - - - - -RETURN 0 - - - Err_Proc: - RETURN 1 - -END - - GO - - - - - - -/* -** -** Created by Date -** -** Blasa 4-5-2024 Process to update Environmental Assessment data set ldk file from Production database. -** -** -** -*/ - - -CREATE Procedure onprc_ehr.p_EnvironmentalHistoricalUpdates - - - - AS - - -BEGIN - -IF exists (Select * from onprc_ehr.Environmental_Assessment) -BEGIN ----Update Testing location syntax - -Update ss -set ss.testing_location = 'COL SW' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Col. SW' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Annex Rm 1', - ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Annex Rm 1' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'COL SW', - ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Colony SW' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Catch Area 2', - ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Catch 2' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Pens Run 1 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 1' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Pens Run 10 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 10' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Pens Run 11 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 11' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Pens Run 12 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 12' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Pens Run 2 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 2' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Pens Run 3 Lixit' - - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 3' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Pens Run 4 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 4' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Pens Run 5 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 5' - - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Pens Run 6 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 6' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Pens Run 7 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 7' - - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Pens Run 8 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 8' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Pens Run 9 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Pens Run 9' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 1 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 1' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 10 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 10' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 11 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 11' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 12 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 12' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 13 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 13' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 14 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 14' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 15 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 15' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 16 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 16' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'SGH 17 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 17' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 18 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 18' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 19 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 19' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 2 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 2' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 20 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 20' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 21 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 21' - - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'SGH 22 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 22' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 23 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 23' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'SGH 24 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 24' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 25 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 25' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 26 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 26' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 27 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 27' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 28 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 28' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 29 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 29' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 30 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 30' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 3 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 3' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 31 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 31' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 32 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 32' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 4 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 4' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 5 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 5' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 6 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 6' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 7 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 7' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 8 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 8' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 9 Lixit' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 9' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'BOS RM 102' - - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Bosky 102' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'BOS RM 103' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Bosky 103' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'BOS RM 104' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Bosky 104' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'BOS RM 122' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Bosky 122' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'BOS RM 123' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Bosky 123' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Cage Washer Colony Annex toy' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Cage Washer Colony Annex tunnel toy' - - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Cage Washer VGTI Large (Jan/June)' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Cage Washer VGTI Large (semi-annual)' - - - If @@Error <> 0 - GoTo Err_Proc -Update ss -set ss.testing_location = 'Cage Washer VGTI Small (Jan/June)' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Cage Washer VGTI Small (semi-annual)' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Dishwasher Colony North' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Dishwasher N. Colony' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Dishwasher Colony South' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Dishwasher S. Colony' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Annex Rm 37' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Annex room 37' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Catch Area 2' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Catch 2' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Catch Area 5' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Catch 5' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'COL SW' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Col. SW' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'COL NW' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Col. NW' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'COL NW' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Colony NW' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'COL RM 4' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Colony RM 4' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'COL Run 1' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Colony Run 1' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'COL Run 2' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Colony Run 2' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'COL Run 3' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Colony Run 3' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'COL Run 4' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Colony Run 4' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'COL Run 5' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Colony Run 5' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss - set ss.testing_location = 'COL Run 6' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss - where ss.testing_location = 'Colony Run 6' - - - If @@Error <> 0 - GoTo Err_Proc - Update sS - set ss.testing_location = 'COL Run 7' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss - where ss.testing_location = 'Colony Run 7' - - - If @@Error <> 0 - GoTo Err_Proc - - Update ss - set ss.testing_location = 'COL Run 8' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss - where ss.testing_location = 'Colony Run 8' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'COL SW' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Colony SW' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 1' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 1 inside' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'SGH 1' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 1 inside' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'SGH 2' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 2 outside' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 2' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 2 outside' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 29' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 29 inside' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 29' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 29 inside' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 30' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 30 outside' - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'SGH 30' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 30 outside' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Dishwasher Bldg 611 ' - -- ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'SGH 30 outside' - - If @@Error <> 0 - GoTo Err_Proc - -update onprc_ehr.Environmental_Assessment -set testing_location = 'Dishwasher ASA 135' -where testing_location = 'Dishwasher ASA 135 ' - - - If @@Error <> 0 - GoTo Err_Proc - -update onprc_ehr.Environmental_Assessment -set testing_location = 'Dishwasher ASA 136' -where testing_location = 'Dishwasher ASA 136 ' - - If @@Error <> 0 - GoTo Err_Proc - -update onprc_ehr.Environmental_Assessment -set testing_location = 'Dishwasher Bldg 611' -where testing_location = 'Dishwasher Bldg 611 ' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Annex Rm 1' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RM 1' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Annex Rm 34' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RM 34' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Annex Rm 13' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RM 13' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Annex Rm 14' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RM 14' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Annex Rm 15' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RM 15' - - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Annex Rm 16' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RM 16' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Annex Rm 2' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RM 2' - - If @@Error <> 0 - GoTo Err_Proc - - -Update ss -set ss.testing_location = 'Annex Rm 34' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RM 34' - - - If @@Error <> 0 - GoTo Err_Proc -Update ss -set ss.testing_location = 'Annex Rm 39' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RM 39' - - - If @@Error <> 0 - GoTo Err_Proc -Update ss -set ss.testing_location = 'Annex Rm 4' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RM 4' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss - set ss.testing_location = 'Annex Run 1' - from onprc_ehr.Environmental_Assessment ss - where ss.testing_location = 'AN RUN 1' - - - If @@Error <> 0 - GoTo Err_Proc -Update ss -set ss.testing_location = 'Annex Run 2' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RUN 2' - - - If @@Error <> 0 - GoTo Err_Proc -Update ss -set ss.testing_location = 'Annex Run 3' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RUN 3' - - - If @@Error <> 0 - GoTo Err_Proc -Update ss -set ss.testing_location = 'Annex Run 30' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'AN RUN 30' - - - If @@Error <> 0 - GoTo Err_Proc - -Update ss -set ss.testing_location = 'Col Run 7E' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location = 'Col Run 7 E' - - If @@Error <> 0 - GoTo Err_Proc - ------- Update only locations designated as Clinpath locations. - -Update ss -set ss.charge_unit = 'Clinpath' - from onprc_ehr.Environmental_Assessment ss -where ss.testing_location in (select distinct value from onprc_ehr.Environmental_Reference_Data where columnname = 'testlocation') - - If @@Error <> 0 - GoTo Err_Proc - ------------ Update only locations designated as Kati's Room LocationXXXX - -update onprc_ehr.Environmental_Assessment -set testing_location = 'Col Run 7A' -where testing_location = 'Col Run 7 A' - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Col Run 7B' -where testing_location = 'Col Run 7 B' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Col Run 7D' -where testing_location = 'Col Run 7 D' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Colony Rm 2 (Clinic)' -where testing_location = 'Colony Rm 2 Clinic' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Pens RM 102A (Clinic)' -where testing_location = 'Pens Rm 102A (Clinic)' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Pens RM 104 (Feed)' -where testing_location = 'PENS Rm 104 (Feed Room)' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Pens RM 104 (Feed)' -where testing_location = 'Pens RM 104 (Feed )' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'VGTI 0120 (clean cage wash)' -where testing_location = 'VGTI 0120 (clean cage wash' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Col Run 6A' -where testing_location = 'Col Run 6 A' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Col Run 6C' -where testing_location = 'Col Run 6 C' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'ASB 3 Cage Wash' -where testing_location = 'ASB 3 Cage Wash Area' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'ASB 1 Cage Wash' -where testing_location = 'ASB 1 Cage Wash Area' - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Cage Washer ASB 1 cage' -where testing_location = 'Cage Washer ASB 1' - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Cage Washer VGTI Large (Jan/June)' -where testing_location = 'Cage Washer VGTI Large' - - - - If @@Error <> 0 - GoTo Err_Proc -update onprc_ehr.Environmental_Assessment -set testing_location = 'Cage Washer VGTI Small (Jan/June)' -where testing_location = 'Cage Washer VGTI Small' - - - If @@Error <> 0 - GoTo Err_Proc - -END ----if exists - - - -RETURN 0 - - - Err_Proc: - RETURN 1 - -END - -GO - - - diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.011-23.012.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.011-23.012.sql deleted file mode 100644 index 06353255d..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.011-23.012.sql +++ /dev/null @@ -1,52 +0,0 @@ --- Alter the stored proc -/****** Object: StoredProcedure [onprc_ehr].[MPA_ClnRemarkAddition] Script Date: 5/17/2024 *****/ --- ================================================================================= --- Author: Lakshmi Kolli --- Create date: 5/17/2024 --- Description: Altering the procedure with the new ONPRC email address --- ================================================================================= - -ALTER PROCEDURE [onprc_ehr].[MPA_ClnRemarkAddition] -AS - -DECLARE -@MPACount Int, -@taskId nvarchar(4000), -@displayName nvarchar(250) - -BEGIN - --Delete all rows from the temp_Drug table - Delete From onprc_ehr.Temp_ClnRemarks - - --Check if the MPA injection E-85760 was administered today - Select @MPACount = COUNT(*) From studyDataset.c6d178_drug - Where code = 'E-85760' And CONVERT(DATE, date) = CONVERT(DATE, GETDATE()) And qcstate = 18 - - --Found entries, so, enter the clinical remarks now - If @MPACount > 0 - Begin - -- Get the displayName for user: onprc-is from core.users table - Select @displayName = displayName from core.users where userid = 1003 - - -- Create a Task entry in ehr.tasks table - Set @taskid = NEWID() -- creating taskid - Insert Into ehr.tasks - (taskid, category, title, formtype, qcstate, assignedto, duedate, createdby, created, - container, modifiedby, modified, description, datecompleted) - Values - (@taskid, 'Task', 'Bulk Clinical Entry', 'Bulk Clinical Entry', 18, 1003, GETDATE(), 1003, GETDATE(), - 'CD17027B-C55F-102F-9907-5107380A54BE', 1003, GETDATE(), 'Created by the ETL process', GETDATE()) - - --Insert the clinical remark into the temp clinical remarks table. - /* Get all the Animals who had MPA injection today from studyDataset.c6d178_drug - and INSERT the data into the studyDataset.c6d185_clinremarks table */ - Insert Into onprc_ehr.Temp_ClnRemarks ( - date, qcstate, participantid, project, remark, p, performedby, category, taskid, createdby, modifiedby - ) - Select GETDATE(), 18, participantid, project, 'Remark entered by the ETL process', 'MPA injection administered', @displayName, 'Clinical', @taskId, 1003, 1003 - From studyDataset.c6d178_drug - Where code = 'E-85760' And CONVERT(DATE, date) = CONVERT(DATE, GETDATE()) And qcstate = 18 - End -END - -GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.012-23.013.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.012-23.013.sql deleted file mode 100644 index ec0d44e27..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.012-23.013.sql +++ /dev/null @@ -1,281 +0,0 @@ -CREATE TABLE [onprc_ehr].[TB_TestTemp]( - [rowid] [int] IDENTITY(100,1) NOT NULL, - animalid varchar(200) NULL, - date datetime NULL, - objectid ENTITYID NOT NULL, - created datetime NULL, - createdby integer NULL, - performedby varchar(200) NULL - - - ) - GO - -CREATE TABLE [onprc_ehr].[TB_TestTempMaster]( - rowid integer , - animalid varchar(200) NULL, - date datetime NULL, - objectid ENTITYID NOT NULL, - created datetime NULL, - createdby integer NULL, - performedby varchar(200) NULL - - - ) - GO - - - - - -/* -** -** Created by -** R. Blasa 6-5-2024 A Program Process that reviews all TB Test entries on a given date, and creates a -** new TB Test Clinical Observation record based on -** having the same monkey id, date, and to be assigned to a Data Admin for reviews. -** -** -*/ - -CREATE Procedure onprc_ehr.p_Create_TB_Observationrecords - - - - AS - - - -DECLARE - @SearchKey Int, - @TempsearchKey Int, - @TaskId varchar(4000), - @ObjectId varchar(4000), - @AnimalID varchar(100), - @date datetime, - @createdby smallint, - @created smalldatetime, - @performedby varchar(200), - @RunID varchar(4000) - - - - -BEGIN - - - - ---- Reset temp table - -Truncate table onprc_ehr.TB_TestTemp - - - If @@Error <> 0 - GoTo Err_Proc - - - --- Generate a list TB test monkeys ) - - Insert into onprc_ehr.TB_TestTemp - -select - a.participantid, - a.date, - a.objectid, - a.created, - a.createdBy, - a.performedby - - - - -from studydataset.c6d214_encounters a -Where a.participantid not in (select b.participantid from studydataset.c6d171_clinical_observations b - where a.participantid = b.participantid And cast(a.date as date) = dateadd(day,3,cast(b.date as date)) And b.category = 'TB TST Score (72 hr)' ) - And a.type = 'Procedure' And a.qcstate = 18 And procedureid = 802 -----'TB Test Intradermal' - And a.created >= dateadd(day, -1, cast(getdate() as date)) -And a.participantid in ( select k.participantid from studydataset.c6d203_demographics k - where k.calculated_status = 'alive') - -order by a.participantid, a.date desc - - - If @@Error <> 0 - GoTo Err_Proc - - ---- When there are no records to process, exit immediately from the program. - - If (Select count(*) from onprc_ehr.TB_TestTemp) = 0 - -BEGIN -GOTO No_Records -END - - - ---- Reset temp variables - - Set @SearchKey = 0 - Set @TempSearchKey = 0 - Set @Date = NULL - Set @created = NULL - Set @createdby =NULL - Set @performedby = NULL - Set @TaskID = NULL - Set @Animalid = Null - Set @RunID = Null - - - - ----- extract initial row id - -Select Top 1 @Searchkey = rowid from onprc_ehr.TB_TestTemp -Order by rowid - - - While @TempSearchKey < @SearchKey -BEGIN - - -----Begin entry Tb observation process - -Select @Animalid =animalid, @date = date, @created =created, @createdby =createdby,@performedby= performedby from onprc_ehr.TB_TestTemp Where rowid = @Searchkey - - If not exists (select * from studydataset.c6d171_clinical_observations j Where j.participantid = @AnimalID - And cast(j.date as date) = dateadd(day,3,cast(@date as date)) And j.category = 'TB TST Score (72 hr)' ) -BEGIN - - - - Set @TaskID = NEWID() ----- Task Record Object ID - Set @RunID = NEWID() ---- ObjectID - Set @date = dateadd(day, 3,@date) ----- Add three days from TB Test date - - - - ---- Generate a Task id record - - Insert into EHR.Tasks - ( - taskid, - description, - title, - qcstate, - formType, - category, - container, - assignedto, - created, - createdby, - modified, - modifiedby - - ) - - Values ( - - @TaskID, - @AnimalID + ' ' + cast(@Date as varchar(50)) , ------ Title consist of animal id and Clinical procedure date - 'TB TST Scores', - 20, --- Qc State (In Progress) - 'TB TST Scores', ------ FormType - 'task', ----- category, - 'CD17027B-C55F-102F-9907-5107380A54BE', ---- EHR Container - 1822, -------- Assigned To Data Admins - getdate(), ------- Create Date - @createdby, -------- Created By - getdate(), ------- Modified Date - @createdby ----- Modified by - - ) - - If @@Error <> 0 - GoTo Err_Proc - - - - --- Create a Clinical Observation Record - - Insert into studydataset.c6d171_clinical_observations - ( - participantid, - date, - category, - area, - observation, - created, - createdby, - performedby, - objectid, - taskid, - qcstate, - modified, - modifiedby, - lsid - - ) - values ( - @animalid, - @date, - 'TB TST Score (72 hr)', - 'Right Eyelid', - 'Grade: Negative', - getdate(), ----- created - @createdby, - @performedby, - @RunID , ----- Objectid - @TaskID, - 20 , ---- In Progress QCState - getdate(), -----modified - @createdBy, - 'urn:lsid:ohsu.edu:Study.Data-6:5006.10003.19810204.0000.' + '' + @RunID + '' - - ) - - If @@Error <> 0 - GoTo Err_Proc - - - -END - - - ----- Proceed and fetch the next record - - Set @TempSearchKey = @SearchKey - -Select Top 1 @SearchKey = rowid from onprc_ehr.TB_TestTemp -Where rowid > @TempSearchKey -Order by rowid - - -END ---- While @TempSearchKey - - - ----- Create a master copy of the completed transaction - - Insert into onprc_ehr.TB_TestTempMaster - Select * from onprc_ehr.TB_TestTemp - - If @@Error <> 0 - GoTo Err_Proc - - - -No_Records: - - RETURN 0 - - -Err_Proc: - -------Error Generated, program processed stopped - RETURN 1 - - -END - -GO - - - - - - diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.014-23.015.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.014-23.015.sql deleted file mode 100644 index d60c7e407..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.014-23.015.sql +++ /dev/null @@ -1,261 +0,0 @@ - - - - - -/* -** -** Created by -** R. Blasa 6-5-2024 A Program Process that reviews all TB Test entries on a given date, and creates a -** new TB Test Clinical Observation record based on -** having the same monkey id, date, and to be assigned to a Data Admin for reviews. -** -** R. Blasa Modified program so that each Clinical Observation entries generated by the program is assigned -** only a single task id when the program executes daily. -** -** -*/ - - ALTER Procedure onprc_ehr.p_Create_TB_Observationrecords - - - - AS - - - -DECLARE - @SearchKey Int, - @TempsearchKey Int, - @TaskId varchar(4000), - @ObjectId varchar(4000), - @AnimalID varchar(100), - @date datetime, - @createdby smallint, - @created smalldatetime, - @performedby varchar(200), - @RunID varchar(4000) - - - - -BEGIN - - - - ---- Reset temp table - -Truncate table onprc_ehr.TB_TestTemp - - - If @@Error <> 0 - GoTo Err_Proc - - - --- Generate a list TB test monkeys ) - - Insert into onprc_ehr.TB_TestTemp - -select - a.participantid, - a.date, - a.objectid, - a.created, - a.createdBy, - a.performedby - - - - -from studydataset.c6d214_encounters a -Where a.participantid not in (select b.participantid from studydataset.c6d171_clinical_observations b - where a.participantid = b.participantid And cast(a.date as date) = dateadd(day,3,cast(b.date as date)) And b.category = 'TB TST Score (72 hr)' ) - And a.type = 'Procedure' And a.qcstate = 18 And procedureid = 802 -----'TB Test Intradermal' - And a.created >= dateadd(day, -1, cast(getdate() as date)) -And a.participantid in ( select k.participantid from studydataset.c6d203_demographics k - where k.calculated_status = 'alive') - -order by a.participantid, a.date desc - - - If @@Error <> 0 - GoTo Err_Proc - - ---- When there are no records to process, exit immediately from the program. - - If (Select count(*) from onprc_ehr.TB_TestTemp) = 0 - BEGIN - GOTO No_Records - END - - - ---- Reset temp variables - - Set @SearchKey = 0 - Set @TempSearchKey = 0 - Set @Date = NULL - Set @created = NULL - Set @createdby =NULL - Set @performedby = NULL - Set @TaskID = NULL - Set @Animalid = Null - Set @RunID = Null - - - - ----- extract initial row id - - Select Top 1 @Searchkey = rowid from onprc_ehr.TB_TestTemp - Order by rowid - - - Set @TaskID = NEWID() ----- Task Record Object ID - - ----Create a single task for each daily process - - - Insert into EHR.Tasks - ( - taskid, - description, - title, - qcstate, - formType, - category, - container, - assignedto, - created, - createdby, - modified, - modifiedby - - ) - - Values ( - - @TaskID, - 'TB TST Scores ' + cast(@Date as varchar(50)) , ------ Title consist of animal id and Clinical procedure date - 'TB TST Scores', - 20, --- Qc State (In Progress) - 'TB TST Scores', ------ FormType - 'task', ----- category, - 'CD17027B-C55F-102F-9907-5107380A54BE', ---- EHR Container - 1822, -------- Assigned To Data Admins - getdate(), ------- Create Date - 1042, -------- Created By IS - getdate(), ------- Modified Date - 1042 ----- Modified by IS - - ) - - If @@Error <> 0 - GoTo Err_Proc - - - - While @TempSearchKey < @SearchKey - BEGIN - - -----Begin entry Tb observation process - - Select @Animalid =animalid, @date = date, @created =created, @createdby =createdby,@performedby= performedby from onprc_ehr.TB_TestTemp Where rowid = @Searchkey - - If not exists (select * from studydataset.c6d171_clinical_observations j Where j.participantid = @AnimalID - And cast(j.date as date) = dateadd(day,3,cast(@date as date)) And j.category = 'TB TST Score (72 hr)' ) - BEGIN - - - - ----- Initialize data entries - Set @RunID = NEWID() ---- ObjectID - Set @date = dateadd(day, 3,@date) ----- Add three days from TB Test date - - - - --- Create a Clinical Observation Record - - Insert into studydataset.c6d171_clinical_observations - ( - participantid, - date, - category, - area, - observation, - created, - createdby, - performedby, - objectid, - taskid, - qcstate, - modified, - modifiedby, - lsid - - ) - values ( - @animalid, - @date, - 'TB TST Score (72 hr)', - 'Right Eyelid', - 'Grade: Negative', - getdate(), ----- created - @createdby, - @performedby, - @RunID , ----- Objectid - @TaskID, - 20 , ---- In Progress QCState - getdate(), -----modified - @createdBy, - 'urn:lsid:ohsu.edu:Study.Data-6:5006.10003.19810204.0000.' + '' + @RunID + '' - - ) - - If @@Error <> 0 - GoTo Err_Proc - - - -END - - - ----- Proceed and fetch the next record - - Set @TempSearchKey = @SearchKey - -Select Top 1 @SearchKey = rowid from onprc_ehr.TB_TestTemp -Where rowid > @TempSearchKey -Order by rowid - - -END ---- While @TempSearchKey - - - ----- Create a master copy of the completed transaction - - Insert into onprc_ehr.TB_TestTempMaster - Select * from onprc_ehr.TB_TestTemp - - If @@Error <> 0 - GoTo Err_Proc - - - -No_Records: - - RETURN 0 - - -Err_Proc: - -------Error Generated, program processed stopped - RETURN 1 - - -END - -GO - - - - - - diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.015-23.016.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.015-23.016.sql deleted file mode 100644 index dfefdcc84..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-23.015-23.016.sql +++ /dev/null @@ -1,266 +0,0 @@ - - - - - -/* -** -** Created by -** R. Blasa 6-5-2024 A Program Process that reviews all TB Test entries on a given date, and creates a -** new TB Test Clinical Observation record based on -** having the same monkey id, date, and to be assigned to a Data Admin for reviews. -** -** R. Blasa Modified program so that each Clinical Observation entries generated by the program is assigned -** only a single task id when the program executes daily. -** -** -*/ - - ALTER Procedure onprc_ehr.p_Create_TB_Observationrecords - - - - AS - - - -DECLARE - @SearchKey Int, - @TempsearchKey Int, - @TaskId varchar(4000), - @ObjectId varchar(4000), - @AnimalID varchar(100), - @date datetime, - @createdby smallint, - @created smalldatetime, - @performedby varchar(200), - @RunID varchar(4000) - - - - -BEGIN - - - - ---- Reset temp table - -Truncate table onprc_ehr.TB_TestTemp - - - If @@Error <> 0 - GoTo Err_Proc - - - --- Generate a list TB test monkeys ) - - Insert into onprc_ehr.TB_TestTemp - -select - a.participantid, - a.date, - a.objectid, - a.created, - a.createdBy, - a.performedby - - - - -from studydataset.c6d214_encounters a -Where a.participantid not in (select b.participantid from studydataset.c6d171_clinical_observations b - where a.participantid = b.participantid - And cast(b.date as date) = dateadd(day,3,cast(a.date as date)) - And b.category = 'TB TST Score (72 hr)' - And a.created >= cast(getdate() as date) - And a.type = 'Procedure' And a.qcstate = 18 And a.procedureid = 802 ) - - And a.type = 'Procedure' And a.qcstate = 18 And a.procedureid = 802 -----'TB Test Intradermal' - And a.created >= cast(getdate() as date) -And a.participantid in ( select k.participantid from studydataset.c6d203_demographics k - where k.calculated_status = 'alive') - -order by a.participantid, a.date desc - - - If @@Error <> 0 - GoTo Err_Proc - - ---- When there are no records to process, exit immediately from the program. - - If (Select count(*) from onprc_ehr.TB_TestTemp) = 0 - BEGIN - GOTO No_Records - END - - - ---- Reset temp variables - - Set @SearchKey = 0 - Set @TempSearchKey = 0 - Set @Date = NULL - Set @created = NULL - Set @createdby =NULL - Set @performedby = NULL - Set @TaskID = NULL - Set @Animalid = Null - Set @RunID = Null - - - - ----- extract initial row id - - Select Top 1 @Searchkey = rowid from onprc_ehr.TB_TestTemp - Order by rowid - - - Set @TaskID = NEWID() ----- Task Record Object ID - - ----Create a single task for each daily process - - - Insert into EHR.Tasks - ( - taskid, - description, - title, - qcstate, - formType, - category, - container, - assignedto, - created, - createdby, - modified, - modifiedby - - ) - - Values ( - - @TaskID, - 'TB TST Scores ' + cast(@Date as varchar(50)) , ------ Title consist of animal id and Clinical procedure date - 'TB TST Scores', - 20, --- Qc State (In Progress) - 'TB TST Scores', ------ FormType - 'task', ----- category, - 'CD17027B-C55F-102F-9907-5107380A54BE', ---- EHR Container - 1822, -------- Assigned To Data Admins - getdate(), ------- Create Date - 1042, -------- Created By IS - getdate(), ------- Modified Date - 1042 ----- Modified by IS - - ) - - If @@Error <> 0 - GoTo Err_Proc - - - - While @TempSearchKey < @SearchKey - BEGIN - - -----Begin entry Tb observation process - - Select @Animalid =animalid, @date = date, @created =created, @createdby =createdby,@performedby= performedby from onprc_ehr.TB_TestTemp Where rowid = @Searchkey - - If not exists (select * from studydataset.c6d171_clinical_observations j Where j.participantid = @AnimalID - And cast(j.date as date) = dateadd(day,3,cast(@date as date)) And j.category = 'TB TST Score (72 hr)' ) - BEGIN - - - - ----- Initialize data entries - Set @RunID = NEWID() ---- ObjectID - Set @date = dateadd(day, 3,@date) ----- Add three days from TB Test date - - - - --- Create a Clinical Observation Record - - Insert into studydataset.c6d171_clinical_observations - ( - participantid, - date, - category, - area, - observation, - created, - createdby, - performedby, - objectid, - taskid, - qcstate, - modified, - modifiedby, - lsid - - ) - values ( - @animalid, - @date, - 'TB TST Score (72 hr)', - 'Right Eyelid', - 'Grade: Negative', - getdate(), ----- created - @createdby, - @performedby, - @RunID , ----- Objectid - @TaskID, - 20 , ---- In Progress QCState - getdate(), -----modified - @createdBy, - 'urn:lsid:ohsu.edu:Study.Data-6:5006.10003.19810204.0000.' + '' + @RunID + '' - - ) - - If @@Error <> 0 - GoTo Err_Proc - - - -END - - - ----- Proceed and fetch the next record - - Set @TempSearchKey = @SearchKey - -Select Top 1 @SearchKey = rowid from onprc_ehr.TB_TestTemp -Where rowid > @TempSearchKey -Order by rowid - - -END ---- While @TempSearchKey - - - ----- Create a master copy of the completed transaction - - Insert into onprc_ehr.TB_TestTempMaster - Select * from onprc_ehr.TB_TestTemp - - If @@Error <> 0 - GoTo Err_Proc - - - -No_Records: - - RETURN 0 - - -Err_Proc: - -------Error Generated, program processed stopped - RETURN 1 - - -END - -GO - - - - - - diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.001-24.002.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.001-24.002.sql deleted file mode 100644 index 79c8ec8b6..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.001-24.002.sql +++ /dev/null @@ -1,7 +0,0 @@ ---added to allow insert of calculated fields from eIACUC - ---2024-12-13 In development need to use a drop if exists statement for these to run - -ALTER TABLE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS ADD [BaseProtocol] varchar(100) Null; -ALTER TABLE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS ADD [RevisionNumber] varchar(100) Null; -ALTER TABLE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS ADD [NewestRecord] INT Null; \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.002-24.003.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.002-24.003.sql deleted file mode 100644 index 0b8089f6f..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.002-24.003.sql +++ /dev/null @@ -1,34 +0,0 @@ -CREATE PROCEDURE onprc_ehr.BaseProtocol -AS -BEGIN - -- Create a Common Table Expression (CTE) named BaseProtocol - WITH BaseProtocol AS - ( - SELECT - RowID, - Protocol_id, - -- Determine the BaseProtocol based on the length of the Protocol_id - CASE - WHEN LEN(Protocol_id) > 10 THEN SUBSTRING(Protocol_id, 6, 15) - ELSE Protocol_id - END AS BaseProtocol, - -- Determine the RevisionNumber based on the length of the Protocol_id - CASE - WHEN LEN(Protocol_id) > 10 THEN SUBSTRING(Protocol_id,1, 5) - ELSE 'Original' - END AS RevisionNumber, - approval_date, - Three_Year_Expiration, - last_modified, - Protocol_State - FROM onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS - ) - - -- Update the onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS table with BaseProtocol and RevisionNumber from the CTE - UPDATE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS - SET BaseProtocol = BaseProtocol.BaseProtocol, - RevisionNumber = BaseProtocol.RevisionNumber - FROM BaseProtocol - WHERE onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS.RowID = BaseProtocol.RowID; -END -GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.004-24.005.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.004-24.005.sql deleted file mode 100644 index d6bc68d98..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.004-24.005.sql +++ /dev/null @@ -1,48 +0,0 @@ -GO -/****** Object: StoredProcedure [onprc_ehr].[ExpiredProtocolUpdate] Script Date: 12/20/2024 9:09:09 AM ******/ -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -CREATE PROCEDURE [onprc_ehr].[ExpiredProtocolUpdate] - AS -BEGIN - -WITH ApprovedProtocols AS ( - SELECT - BaseProtocol, - MAX(Approval_Date) AS maxApprovalDate - FROM - onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS - WHERE - Protocol_State IN ('approved','expired', 'terminated') - GROUP BY - BaseProtocol -), - - - DistinctProtocols AS ( - SELECT DISTINCT - p.rowID, - p.BaseProtocol, - p.RevisionNumber, - p.Protocol_State, - p.Approval_Date, - p.Last_Modified, - p.Three_Year_Expiration - FROM - onprc_ehr.eIACUC_PRIME_VIEW_PROTOCOLS p - INNER JOIN ApprovedProtocols ap ON p.BaseProtocol = ap.BaseProtocol - AND p.Approval_Date = ap.maxApprovalDate), - ExpiredProtocol AS ( - Select - d.*, - p.protocol, - p.enddate - from DistinctProtocols d inner join ehr.protocol p on d.BaseProtocol = p.external_ID - where d.Protocol_State != 'Approved' and p.enddate is Null) - -Update p - Set p.enddate = getDate() - from ehr.protocol p inner join expiredProtocol e on p.external_id = e.BaseProtocol -END diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.005-24.006.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.005-24.006.sql deleted file mode 100644 index 3a7cb2a6b..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.005-24.006.sql +++ /dev/null @@ -1,14 +0,0 @@ -CREATE TABLE onprc_ehr.procedure_default_blood ( - rowid int identity(1,1), - procedureid int, - sampletype varchar(300) Null, - additionalServices varchar(1000) Null, - reason varchar(300) Null, - instructions varchar(2000) Null, - chargetype varchar(400) Null - - - CONSTRAINT PK_procedure_default_blood PRIMARY KEY (rowid) -) - -GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.006-24.007.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.006-24.007.sql deleted file mode 100644 index 0595110af..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.006-24.007.sql +++ /dev/null @@ -1,224 +0,0 @@ - - -CREATE TABLE [onprc_ehr].[Rpt_AnimalID_Weights]( - searchid int IDENTITY(100,1) NOT NULL, - animalID varchar(100) NULL, - date smalldatetime NULL, - weight decimal(12,5) NULL, - taskId ENTITYID NULL, - created smalldatetime NULL, - createdby smallint NULL, - modified smalldatetime NULL, - modifiedby smallint NULL - - ) ON [PRIMARY] - - GO - - -CREATE TABLE [onprc_ehr].[Rpt_AnimalID_WeightsMaster]( - searchid int IDENTITY(100,1) NOT NULL, - rowid int, - animalID varchar(100) NULL, - date smalldatetime NULL, - weight decimal(12,5) NULL, - taskId ENTITYID NULL, - created smalldatetime NULL, - createdby smallint NULL, - modified smalldatetime NULL, - modifiedby smallint NULL, - actual_created smalldatetime NULL, - remark varchar(1000) NULL - - ) ON [PRIMARY] - - GO - - -/* -** -** Created by Date -** -** Blasa 1-29-2025 Extract the Pathology Tissue Weights from Pathology Tissue records. -** -** T-00010 BODY AS A WHOLE Tissue_Samples data set -** -** -** -** -** -** -** -*/ - - -CREATE Procedure onprc_ehr.sp_PathologyTissueWeightsProcess - @StartDate SmallDateTime, - @EndDate SmallDateTime - - - - - AS - - - -DECLARE @ReturnValue Int, - @SearchKey Int, - @TempsearchKey Int, - @AnimalID varchar(100), - @Date smalldatetime, - @RunID varchar(4000) - - -Begin - - - ----- Reset Temp Table - - Set @Returnvalue = 0 - - - ----- Reset Temp tables - Delete onprc_ehr.Rpt_AnimalID_Weights - - - If @@Error <> 0 - GoTo Err_Proc - - - - Insert into onprc_ehr.Rpt_AnimalID_Weights -select - e.participantid, - e.date, - e.weight, - e.taskid, - e.created, - e.createdby, - e.modified, - e.modifiedby - - -from studydataset.c6d174_tissue_samples e -where e.tissue = 'T-00010' - And (e.date >= @StartDate And e.date < Dateadd(day,1,@EndDate) ) - - and e.qcstate = 18 - and e.weight is not null -order by date desc - - - - - If @@Error <> 0 - GoTo Err_Proc - - -Set @TempsearchKey = 0 -Set @SearchKey = 0 - -Select Top 1 @Searchkey = Searchid from onprc_ehr.Rpt_AnimalID_Weights -Order by SearchID - - - - - - While @TempSearchKey < @SearchKey - Begin - - ---- Reset temp variables - Set @AnimalID = null - Set @Date = null - Set @RunID = null - - ----Extract primary weights data from Pathology records - - Select @Animalid = animalid, @Date = date from onprc_ehr.Rpt_AnimalID_Weights where searchid = @Searchkey - - ---- Create Weights entries - - If not exists(select * from studydataset.c6d175_weight - Where participantid = @AnimalID And date = @Date ) - - - Begin - ----- Set record object id - Set @RunID = NEWID() - - Insert into studydataset.c6d175_weight - (participantid, - date, - weight, - qcstate, - created, - createdby, - modified, - modifiedby, - taskid, - objectid, - remark, - lsid - ) - - Select @AnimalID, - @Date, - Rpt.weight/1000, ----- convert weight from grams to Kilograms - 18, ------ default QC State - Rpt.created, - Rpt.createdby, - Rpt.modified, - Rpt.modifiedby, - Rpt.taskid, - @RunID, ------- record object id - 'Weight added from Path Tissue records', - ' urn:lsid:ohsu.edu:Study.Data-6:1045.' + @AnimalID + '.' + format(cast(@date as date), 'yyyyMMdd') + '.0000.' + @RunID + '' - - - - from onprc_ehr.Rpt_AnimalID_Weights Rpt - where searchid = @Searchkey - - If @@Error <> 0 - GoTo Err_Proc - - - - End ---- - - - - - Set @TempSearchkey = @SearchKey - - - Select Top 1 @Searchkey = Searchid from onprc_ehr.Rpt_AnimalID_Weights - Where Searchid > @TempSearchkey - Order by Searchid - - - - - End -----(While) - - ------- Create a Master log of entries - - Insert into onprc_ehr.Rpt_AnimalID_WeightsMaster - Select j.*, - getdate(), ---- record created date - 'Pathology Tissue Weight entry' - - from onprc_ehr.Rpt_AnimalID_Weights j - - - RETURN 0 - -Err_Proc: - - Return 1 - - -END - - diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.007-24.008.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.007-24.008.sql deleted file mode 100644 index f7852d83c..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.007-24.008.sql +++ /dev/null @@ -1,131 +0,0 @@ --- ======================================================================================================================================= --- Author: Lakshmi Kolli --- Create date: 2025-03-04 --- Description: Db tables creation for Prima cassette project. Created all the Prima tables in Prime onprc_ehr schema folder. --- Refer to tkt #11937 --- ======================================================================================================================================= - ---Drop if exists. We are using these 4 tables for the Cassette Project -EXEC core.fn_dropifexists 'Prima_Animals','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_CassetteBases','onprc_ehr','TABLE'; -- Drop this table and create again -EXEC core.fn_dropifexists 'Prima_TissueCollections','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_CaseBase','onprc_ehr','TABLE'; -- Drop this table and create again - ---Drop these tables permanently. We are not using these tables in onprc_ehr. -EXEC core.fn_dropifexists 'Prima_VeterinaryResearchCase','onprc_ehr','TABLE'; --This table doesn't exist anymore in Prima DB -EXEC core.fn_dropifexists 'Prima_CassetteEvents','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_CassetteEventLocations','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_LabstationTypes','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SlideBases','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SlideEvents','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SlideEventLocations','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_StainTests','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_SurgicalWheels','onprc_ehr','TABLE'; -EXEC core.fn_dropifexists 'Prima_UserPersons','onprc_ehr','TABLE'; - -GO - ---Create tables ---1. Animals table -/****** Object: Table [onprc_ehr].[Prima_Animals] ******/ -CREATE TABLE [onprc_ehr].[Prima_Animals]( - [Id] [int] NOT NULL, - [AlternateIdentifier] [nvarchar](63) NULL, - [BreedId] [int] NULL, - [DateOfBirth] [datetime] NULL, - [FecesId] [int] NULL, - [Gender] [tinyint] NOT NULL, - [GeneTarget] [nvarchar](127) NULL, - [GeneticLine] [nvarchar](127) NULL, - [Genotype] [nvarchar](127) NULL, - [Identifier] [nvarchar](127) NULL, - [MannerOfDeathId] [int] NULL, - [RoomNumber] [nvarchar](9) NULL, - [SpeciesId] [int] NOT NULL, - [StomachContentsId] [int] NULL, - [StrainId] [int] NULL, - [DateOfDeath] [datetime] NULL, - [Created] [datetimeoffset](7) NOT NULL, - [OwnerId] [int] NULL, - [Perfuse] [bit] NOT NULL, - [SampleType] [tinyint] NOT NULL - ) -; - ---2. TissueCollections table -/****** Object: Table [onprc_ehr].[Prima_TissueCollections] ******/ -CREATE TABLE [onprc_ehr].[Prima_TissueCollections]( - [Id] [int] NOT NULL, - [Constant] [tinyint] NULL, - [IsWholeAnimal] [bit] NOT NULL, - [SpeciesId] [int] NOT NULL, - [SpecimenType] [int] NOT NULL, - [CreatedByUserId] [int] NOT NULL, - [Deleted] [datetimeoffset](7) NULL, - [DeletedByUserId] [int] NULL, - [NextVersionId] [int] NULL, - [PreviousVersionId] [int] NULL, - [Title] [nvarchar](127) NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [LastModified] [timestamp] NOT NULL, - [Abbreviation] [nvarchar](127) NULL - ) -; - ---3. CaseBase table -/****** Object: Table [onprc_ehr].[Prima_CaseBase] ******/ -CREATE TABLE [onprc_ehr].[Prima_CaseBase]( - [Id] [int] NOT NULL, - [DifferentialDiagnosisId] [int] NULL, - [PathologistId] [int] NULL, - [PriorityLevelId] [int] NOT NULL, - [ResidentPathologistId] [int] NULL, - [SerialNumber] [int] NOT NULL, - [SurgeryDate] [datetime] NULL, - [SurgicalWheelId] [int] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [ResearcherId] [int] NULL, - [StudyId] [int] NULL, - [Discriminator] [nvarchar](128) NULL, - [StudyPhaseId] [int] NULL, - [CohortId] [int] NULL, - [SavedIdentifier] [nvarchar](max) NULL, - [Status] [tinyint] NOT NULL, - [AlternateIdentifier] [nvarchar](24) NULL, - [SurgeryLocationId] [int] NULL, - [ResearchPatientId] [int] NULL, - [AnimalId] [int] NULL, - [ClinicalPatientId] [int] NULL, - [SurgeryAge] [nvarchar](31) NULL - ) -; - ---4. CassetteBases table -/****** Object: Table [onprc_ehr].[Prima_CassetteBases] ******/ -CREATE TABLE [onprc_ehr].[Prima_CassetteBases]( - [Id] [bigint] NOT NULL, - [CassetteColorId] [int] NOT NULL, - [EmbeddingInstructionId] [int] NOT NULL, - [HasTissue] [bit] NOT NULL, - [ProtocolCassetteId] [int] NULL, - [SpecimenBaseId] [bigint] NOT NULL, - [TissueCollectionId] [int] NULL, - [TissueProcessorProgramId] [int] NULL, - [TissueQuantity] [smallint] NOT NULL, - [CaseBaseId] [int] NOT NULL, - [PriorityLevelId] [int] NOT NULL, - [QcStatus] [tinyint] NOT NULL, - [SurgicalSerialPart] [smallint] NOT NULL, - [Created] [datetimeoffset](7) NOT NULL, - [OrderedStatus] [tinyint] NOT NULL, - [SavedIdentifier] [nvarchar](24) NULL, - [BarcodeContent] [nvarchar](72) NULL, - [AlternateIdentifier] [nvarchar](63) NULL, - [PrintStatus] [tinyint] NOT NULL, - [ItemStatus] [smallint] NOT NULL, - [Hazard] [tinyint] NOT NULL, - [CurrentContainerId] [int] NULL - ) -; - -GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.008-24.009.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.008-24.009.sql deleted file mode 100644 index 19aff6a50..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.008-24.009.sql +++ /dev/null @@ -1,212 +0,0 @@ - -CREATE TABLE onprc_ehr.Rpt_AnimalIDTissues( - [Searchkey] [int] IDENTITY(1,1) NOT NULL, - [animalID] varchar(100) NULL, - [date] smalldatetime NULL - - - ) ON [PRIMARY] - GO - -CREATE TABLE onprc_ehr.Rpt_AnimalIDTissues_Master( - [rowid] [int] IDENTITY(1,1) NOT NULL, - [SearchID] int NULL, - [animalID] varchar(100) NULL, - [date] smalldatetime NULL, - [actual_Created] smalldatetime NUll, - [remarks] varchar(500) - - - ) ON [PRIMARY] - GO - - - -/* -** -** Created by Date -** -** Blasa 4/4/2025 Process to attached Tissues Distribution records to Patholody Tissue records -** -** - -** -** -** -** -** - -** -** -** -*/ - - -CREATE Procedure [onprc_ehr].[sp_RptNecropsyTissueDistributionUpdates] - @StartDate SmallDateTime, - @EndDate SmallDateTime - - - - -AS - - - -DECLARE @ReturnValue Int, - @SearchKey Int, - @TempsearchKey Int, - @TaskId varchar(4000), - @ObjectId Varchar(4000), - @AnimalID varchar(100), - @Date smalldatetime, - @Created smalldatetime, - @Createdby smallint, - @modified smalldatetime, - @modifiedby smallint , - @RunID varchar(4000) - -Begin - - - ----- Reset Temp Table - - Set @Returnvalue = 0 - - - - Delete onprc_ehr.Rpt_AnimalIDTissues - - - If @@Error <> 0 - GoTo Err_Proc - - - ----Create the set of records to process - - Insert into onprc_ehr.Rpt_AnimalIDTissues - select distinct - e.participantid, - e.date - - -from studydataset.c6d265_tissuedistributions e - -Where (e.date >= @StartDate And e.date < Dateadd(day,1,@EndDate) ) - And e.qcstate = 18 -order by e.participantid, e.date - - - - If @@Error <> 0 - GoTo Err_Proc - - - -Set @TempsearchKey = 0 -Set @SearchKey = 0 -Set @TaskID = null - -Select Top 1 @Searchkey = Searchkey from onprc_ehr.Rpt_AnimalIDTissues -Order by Searchkey - - - While @TempSearchKey < @SearchKey -Begin - - ------ Create a task record - - Set @TaskID = NEWID() - - - Insert into EHR.Tasks - ( - taskid, - description, - title, - qcstate, - formType, - category, - container, - assignedto, - created, - createdby, - modified, - modifiedby - - ) - - Values ( - - @TaskID, - 'Path Tissues ' + cast(@Date as varchar(50)) , ------ Title - 'PathologyTissues', - 18, --- Qc State (In Progress) - 'PathologyTissues', ------ FormType - 'task', ----- category, - 'CD17027B-C55F-102F-9907-5107380A54BE', ---- EHR Container - 1693, -------- Assigned To DCM Pathology - getdate(), ------- Created Date - 1042, -------- Created By IS - getdate(), ------- Modified Date - 1042 ----- Modified by IS - - ) - - If @@Error <> 0 - GoTo Err_Proc - - - -Select @AnimalID = rpt.AnimalID, @Date= rpt.date, @Created=TDS.created, @Createdby= TDS.createdby, @modified = TDS.modified -from studydataset.c6d265_tissuedistributions TDS, onprc_ehr.Rpt_AnimalIDTissues Rpt -Where TDS.participantid = Rpt.AnimalID - And TDS.date = RPT.date And Rpt.searchkey = @Searchkey - - -If exists (Select * from studydataset.c6d265_tissuedistributions Where participantid = @AnimalID And date = @date) -Begin - Update TDS - set TDS.taskid = @TaskID - - from studydataset.c6d265_tissuedistributions TDS -Where TDS.participantid = @AnimalID - And TDS.date = @Date - - - If @@Error <> 0 - GoTo Err_Proc - -End -- - - - Set @TempSearchkey = @SearchKey - - -Select Top 1 @Searchkey = Searchkey from onprc_ehr.Rpt_AnimalIDTissues -Where Searchkey > @TempSearchkey -Order by Searchkey - - -End -----(While) - - ------- Create a audit records - -Insert into onprc_ehr.Rpt_AnimalidTissues_Master -Select *, - getdate(), - 'Tissue Distribution entries' -from onprc_ehr.Rpt_AnimalIDTissues - - - RETURN 0 - -Err_Proc: - - Return 1 - - -END - -GO - diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.009-24.010.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.009-24.010.sql deleted file mode 100644 index fd2fbc897..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.009-24.010.sql +++ /dev/null @@ -1,14 +0,0 @@ -CREATE TABLE onprc_ehr.snomed_counter -( - subset nvarchar(255) NOT NULL, - count integer NOT NULL, - prefix nvarchar(10) NOT NULL, - container entityid, - createdby userid, - created DATETIME, - modifiedby userid, - modified DATETIME, - - CONSTRAINT pk_snomed_counter PRIMARY KEY (subset), - CONSTRAINT fk_onprc_snomed_counter_container FOREIGN KEY (container) REFERENCES core.Containers (EntityId) -) \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.010-24.011.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.010-24.011.sql deleted file mode 100644 index ae5b261f9..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.010-24.011.sql +++ /dev/null @@ -1,168 +0,0 @@ -CREATE TABLE onprc_ehr.CenterProjectsTemp( - [searchid] [int] IDENTITY(100,1) NOT NULL, - [project] [smallint] NULL, - [protocol] [smallint] NULL, - [account] [varchar](1000) NULL, - [title] [varchar](2000) NULL, - [research] [smallint] NULL, - [createdby] [smallint] NULL, - [created] [datetime] NULL, - [modified] [datetime] NULL, - [modifiedby] [smallint] NULL, - [startdate] [datetime] NULL, - [enddate] [datetime] NULL, - [displayname] [varchar](1000) NULL, - [investigatorid] [smallint] NULL, - [use_category] [varchar](500) NULL, - [projecttype] [varchar](500) NULL, - [objectid] [varchar](max) NULL, - [date_posted] [datetime] NULL - - ) ON [PRIMARY] - GO - - -/* -** -** Created by -** Blasa 5/31/2025 Process to create Center Projects historical records. First create a complete set -** of currently active records, and after the intitial date, just create a record of entries that -** was recently modified. -** - -** -** -** -** -*/ - -CREATE Procedure onprc_ehr.p_CenterProjectsHistoricalProcess - @InitialDate smalldatetime - - - AS - -BEGIN - - ----- Create a fulle record once only - -IF (cast(getdate() as date) = @InitialDate ) -BEGIN - Insert into onprc_ehr.CenterProjectsTemp - ( - project, - protocol, - account, - title, - research, - createdby, - created, - modified, - modifiedby, - startdate, - enddate, - displayname, - investigatorid, - use_category, - projecttype, - objectid, - date_posted -) - -Select - project, - protocol, - account, - title, - research, - createdby, - created, - modified, - modifiedby, - startdate, - enddate, - name, -----displayname - investigatorid, - use_category, - projecttype, - objectid, - getdate() - - From ehr.project where (enddate is null or enddate >= getdate()) - order by modified - - END - - If @@Error <> 0 - GoTo Err_Proc - - - ------ Create modiified records -if exists(Select * from ehr.project where (enddate is null or enddate >= getdate()) - And modified >= cast(getdate() as date)) -BEGIN - - Insert into onprc_ehr.CenterProjectsTemp - ( - project, - protocol, - account, - title, - research, - createdby, - created, - modified, - modifiedby, - startdate, - enddate, - displayname, - investigatorid, - use_category, - projecttype, - objectid, - date_posted - ) - -Select - project, - protocol, - account, - title, - research, - createdby, - created, - modified, - modifiedby, - startdate, - enddate, - name, -----displayname - investigatorid, - use_category, - projecttype, - objectid, - getdate() - -From ehr.project where (enddate is null or enddate >= getdate()) - And modified >= cast(getdate() as date) -order by modified - - - - If @@Error <> 0 - GoTo Err_Proc - -END ----if - - - RETURN 0 - - -Err_Proc: - -------Error Generated, Transfer process stopped - RETURN 1 - - -END - -GO - diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.011-24.012.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.011-24.012.sql deleted file mode 100644 index 99ab9b02e..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.011-24.012.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE onprc_ehr.CenterProjectsTemp ALTER COLUMN protocol VARCHAR(400); -GO \ No newline at end of file diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.012-24.013.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.012-24.013.sql deleted file mode 100644 index 3fcc21300..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.012-24.013.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE onprc_ehr.pairing_observation_types ( - rowid [int] IDENTITY(100,1) NOT NULL, - value nvarchar(200), - category nvarchar(200), - editorconfig NVARCHAR(MAX), - schemaname nvarchar(200), - queryname nvarchar(200), - valuecolumn nvarchar(200), - Created datetime, - CreatedBy USERID, - Modified datetime, - ModifiedBy USERID, - Container entityId NOT NULL, - - CONSTRAINT PK_ONPRC_EHR_PAIRING_OBSERVATION_TYPES PRIMARY KEY (rowid), - -); -GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.013-24.014.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.013-24.014.sql deleted file mode 100644 index cb3c9c4a9..000000000 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-24.013-24.014.sql +++ /dev/null @@ -1,74 +0,0 @@ - - -/* -** -** Created by -** Blasa 10/8/2025 Process to update birth record;s geogrphic origin data. The "Genetic Ancestry" -** geographic_origin information must override the birth's geographic origin values. -** - -** -** -** -** -*/ - -CREATE Procedure onprc_ehr.p_BirthGeographicOriginUpdates - - as - - -BEGIN - - ----- Process data - - IF exists (select * From studydataset.c6d202_birth bir, studydataset.c6d512_geneticancestry b where bir.participantid = b.participantid - And b.enddate is null - and bir.qcstate = 18 - and b.qcstate = 18 - And bir.geographic_origin <> b.result - And b.result is not null - ) - - - - BEGIN - - ---- Update birth geographic origin - - Update bir - set bir.geographic_origin = b.result, - bir.modified = getdate(), - bir.modifiedby = b.modifiedby ---- ancestry staff - - From studydataset.c6d202_birth bir, studydataset.c6d512_geneticancestry b - where bir.participantid = b.participantid - And b.enddate is null - And bir.qcstate = 18 - And b.qcstate = 18 - And bir.geographic_origin <> b.result - And b.result is not null - - - If @@Error <> 0 - GoTo Err_Proc - -END ---- if - - - - - -RETURN 0 - - - Err_Proc: - -------Error Generated, process stopped - RETURN 1 - - -END - -GO - - diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-25.004-25.005.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-25.004-25.005.sql index 6176c6581..31cb7ca5e 100644 --- a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-25.004-25.005.sql +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-25.004-25.005.sql @@ -121,6 +121,4 @@ Begin END - - - +GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-26.000-26.001.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-26.000-26.001.sql new file mode 100644 index 000000000..8fcff018a --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-26.000-26.001.sql @@ -0,0 +1,364 @@ + +EXEC core.fn_dropifexists 'TB_TestTemp', 'onprc_ehr', 'TABLE', NULL; +GO + +EXEC core.fn_dropifexists 'TB_TestTempMaster', 'onprc_ehr', 'TABLE', NULL; +GO +EXEC core.fn_dropifexists 'Temp_Clinical_Observations', 'onprc_ehr', 'TABLE', NULL; +GO +EXEC core.fn_dropifexists 'Temp_Clinical_Observations_Master', 'onprc_ehr', 'TABLE', NULL; + +EXEC core.fn_dropifexists 'Observation_EHRTasks', 'onprc_ehr', 'TABLE', NULL; +GO + + + + + +CREATE TABLE [onprc_ehr].[TB_TestTemp]( + [rowid] [int] IDENTITY(100,1) NOT NULL, + animalid varchar(200) NULL, + date datetime NULL, + objectid ENTITYID NOT NULL, + created datetime NULL, + createdby integer NULL, + performedby varchar(200) NULL, + modifiedby integer NULL, + date_posted smalldatetime + + +) +GO + + +CREATE TABLE [onprc_ehr].[Temp_Clinical_Observations]( + [rowid] [int] IDENTITY(100,1) NOT NULL, + Id varchar(200) NULL, + date smalldatetime NULL, + category varchar(500) NULL, + area varchar(500) NULL, + observation varchar(500) NULL, + createdby integer NULL, + performedby varchar(500) NULL, + taskid varchar(4000) NULL, + qcstate integer NULL, + modifiedby integer NULL + + +) +GO + +CREATE TABLE [onprc_ehr].[Temp_Clinical_Observations_Master]( + [rowid] [int] IDENTITY(100,1) NOT NULL, + searchid integer NULL, + Id varchar(200) NULL, + date smalldatetime NULL, + category varchar(500) NULL, + area varchar(500) NULL, + observation varchar(500) NULL, + createdby integer NULL, + performedby varchar(500) NULL, + taskid varchar(4000) NULL, + qcstate smallint NULL, + modifiedby smalldatetime NULL, + Posted_date smalldatetime + +) +GO + +CREATE TABLE [onprc_ehr].[Observation_EHRTasks]( + [rowid] [int] IDENTITY(100,1) NOT NULL, + taskid varchar(4000) NULL, + description varchar(500)NULL, + title varchar(500)NULL, + qcstate smallint NULL, + formtype varchar(500) NULL, + category varchar(500) NULL, + assignedto smallint NULL, + createdby smallint NULL, + modifiedby smallint NULL + + +) +GO + + +EXEC core.fn_dropifexists 'p_Create_TB_Observationrecords', 'onprc_ehr', 'PROCEDURE', NULL; +GO + + +/* +** +** Created by +** R. Blasa 6-24-2026 A Program Process that reviews all TB Test Encounter entries on a current date, and creates a +** new TB Test Clinical Observation record based on +** having the same monkey id, date, and then to be assigned to a Data Admin for reviews. +** +** Modified program so that each Clinical Observation entries generated by the program is assigned +** only a single task id when the program executes daily. +** +** +*/ + +CREATE Procedure onprc_ehr.p_Create_TB_Observationrecords + + + +AS + + + +DECLARE + @SearchKey Int, + @TempsearchKey Int, + @TaskId varchar(4000), + @AnimalID varchar(100), + @date smalldatetime, + @createdby integer, + @performedby varchar(500), + @modifiedby integer, + @RunID varchar(4000), + @FirstFlag integer, + @TestDate smalldatetime + + + + +BEGIN + + + ---- Reset temp table + + Truncate table onprc_ehr.TB_TestTemp + + If @@Error <> 0 + GoTo Err_Proc + + Truncate table [onprc_ehr].[Temp_Clinical_Observations] + + If @@Error <> 0 + GoTo Err_Proc + + Truncate table [onprc_ehr].[Observation_EHRTasks] + + If @@Error <> 0 + GoTo Err_Proc + + --- Generate a list TB test monkeys ) + + Insert into onprc_ehr.TB_TestTemp + + select + a.participantid, + a.date, + a.objectid, + a.created, + a.createdBy, + a.performedby, + a.modifiedby, + getdate() -----date processed + + + from studydataset.c6d214_encounters a + Where a.type in ('Procedure','Surgery') + And a.qcstate = 18 + And a.procedureid = 802 -----'TB Test Intradermal' + And a.modified >= cast(getdate() as date) + And a.participantid in ( select k.participantid from studydataset.c6d203_demographics k + where k.calculated_status = 'alive') + AND a.participantid not in (select j.participantid from studydataset.c6d171_clinical_observations j + Where j.participantid = a.participantid + And j.date = dateadd(day,3,a.date) + And j.category = 'TB TST Score (72 hr)' + And j.qcstate = 18 ) + + order by a.participantid, a.date desc + + + If @@Error <> 0 + GoTo Err_Proc + + ---- When there are no records to process, exit immediately from the program. + + If (Select count(*) from onprc_ehr.TB_TestTemp) = 0 + BEGIN + GOTO No_Records + END + + + ---- Reset temp variables + + Set @SearchKey = 0 + Set @TempSearchKey = 0 + Set @Date = NULL + Set @modifiedby = NULL + Set @createdby =NULL + Set @performedby = NULL + Set @TaskID = NULL + Set @Animalid = Null + Set @RunID = Null + Set @FirstFlag = 0 + + + + ----- extract initial row id + + Select Top 1 @Searchkey = rowid from onprc_ehr.TB_TestTemp + Order by rowid + + + + ----Create a single task for each daily process + + + While @TempSearchKey < @SearchKey + BEGIN + + -----Begin entry Tb observation process + + Select @Animalid =animalid, @date = date, @modifiedby=modifiedby, @createdby =createdby,@performedby= performedby + from onprc_ehr.TB_TestTemp Where rowid = @Searchkey + + + + + If not exists (select * from studydataset.c6d171_clinical_observations j Where j.participantid = @AnimalID + And j.date = dateadd(day,3,@date) + And j.category = 'TB TST Score (72 hr)' + And j.qcstate = 18 ) + + BEGIN + + If @FirstFlag != 1 + BEGIN + ---- created a new task id + Set @TaskID = NEWID() + + ---- Create Clinical Observation entries + Insert into onprc_ehr.Observation_EHRTasks + ( + taskid, + description, + title, + qcstate, + formType, + category, + assignedto, + createdby, + modifiedby + + ) + + Values ( + + @TaskID, + 'TB TST Scores ' + cast(@Date as varchar(50)) , ------ Title consist of animal id and Clinical procedure date + 'TB TST Scores', + 20, --- Qc State (In Progress) + 'TB TST Scores', ------ FormType + 'task', ----- category, + 1822, ------- Assigned To Data Admins + 1042, -------- Created By IS + 1042 ----- Modified by IS + + ) + + If @@Error <> 0 + GoTo Err_Proc + + ---Set Task insert process only once per single process + Set @FirstFlag = 1 + + END ---(@FirstFlag) + + + ----- Initialize data entries + Set @date = dateadd(day, 3,@date) ----- Add three days from TB Test date + + + + --- Create a Clinical Observation Record + + Insert into Temp_Clinical_Observations + ( + Id, + date, + category, + area, + observation, + createdby, + performedby, + taskid, + qcstate, + modifiedby + + + ) + values ( + @animalid, + @date, + 'TB TST Score (72 hr)', + 'Right Eyelid', + 'Grade: Negative', + 1042, -----created by IS + @performedby, + @TaskID, + 20 , ---- In Progress QCState + 1042 -----modified by IS + + + ) + + If @@Error <> 0 + GoTo Err_Proc + + + END --(If not exist) + + ----- Proceed and fetch the next record + + Set @TempSearchKey = @SearchKey + + Select Top 1 @SearchKey = rowid from onprc_ehr.TB_TestTemp + Where rowid > @TempSearchKey + Order by rowid + + + END ---- While @TempSearchKey + + + ----- Create a master copy of the completed transaction + + Insert into onprc_ehr.Temp_Clinical_Observations_Master + Select *, getdate() + from onprc_ehr.Temp_Clinical_Observations + + If @@Error <> 0 + GoTo Err_Proc + + + + No_Records: + + RETURN 0 + + + Err_Proc: + -------Error Generated, program processed stopped + RETURN 1 + + +END + +GO + + + + + + + + + + + diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-26.001-26.002.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-26.001-26.002.sql new file mode 100644 index 000000000..9cfc36c69 --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-26.001-26.002.sql @@ -0,0 +1,139 @@ + +CREATE TABLE onprc_ehr.Rpt_TempProblemList( + searchid integer IDENTITY(100,1) NOT NULL, + animalid varchar(200) NULL, + date smalldatetime NULL, + objectid varchar(4000) NULL, + caseid varchar(4000) NULL + + ) ON [PRIMARY] + GO + +CREATE TABLE onprc_ehr.Rpt_TempProblemListMaster( + searchid integer IDENTITY(100,1) NOT NULL, + animalid varchar(200) NULL, + date smalldatetime NULL, + objectid varchar(4000) NULL, + caseid varchar(4000) NULL + +) ON [PRIMARY] + GO + + + + +/* +** +** Created by Date Comment +** +** blasa 7-7-2026 Process to update historical problem list records +** +** +** +**/ + +CREATE Procedure onprc_ehr.s_MasterProblemHistoricalProcess + + +AS + + +declare + + + @TempSearchKey Int, + @Searchkey Int, + @AnimalID varchar(100), + @date smalldatetime, + @objectid varchar(4000), + @caseid varchar(4000) + + +Begin + + + ----- Reset the last two months only + + Delete onprc_ehr.Rpt_TempProblemList + + If @@Error <> 0 + GoTo Err_Proc + + + + Set @Tempsearchkey = 0 + Set @Searchkey = 0 + Set @Animalid = '' + Set @date = null + Set @objectid = null + Set @caseid = null + + --- Set initial processing + + Insert into onprc_ehr.Rpt_TempProblemList + select participantid, + date, + objectid, + caseid + from studydataset.c6d200_problem + Where category = 'Wound' + And subcategory = 'Digit Amputation' + And qcstate = 18 + + Order by participantid + + Select top 1 @SearchKey = searchID from onprc_ehr.Rpt_TempProblemList + Order by searchid + + + While @Tempsearchkey < @SearchKey + Begin + + Set @Animalid = '' + Set @date = null + Set @objectid = null + + select @animalid = animalid, @Date = date, @Objectid = objectid + from Rpt_TempProblemList Where searchid = @Searchkey + + -------Begin updating records + + + Update pb + Set pb.subcategory = 'Digit Removal/Caudectomy' + From studydataset.c6d200_problem pb + Where pb.Participantid = @Animalid + And pb.objectid = @objectid + + + If @@Error <> 0 + GoTo Err_Proc + + + Set @TempSearchkey = @Searchkey + + Select Top 1 @SearchKey = searchid From onprc_ehr.Rpt_TempProblemList + Where searchid > @Tempsearchkey + Order by searchid + + + + + End ------(While @tempsearchkey < @Searchkey) + + ---- Create an audit record of these entries + + insert into onprc_ehr.Rpt_TempProblemListMaster + Select animalid, date, objectid, caseid + from onprc_ehr.Rpt_TempProblemList + + + Return 0 + + Err_Proc: Return 1 + + + +END + +GO diff --git a/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-26.002-26.003.sql b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-26.002-26.003.sql new file mode 100644 index 000000000..5159b21df --- /dev/null +++ b/onprc_ehr/resources/schemas/dbscripts/sqlserver/onprc_ehr-26.002-26.003.sql @@ -0,0 +1,255 @@ +SET +QUOTED_IDENTIFIER ON; +GO + +ALTER PROCEDURE +[audit].[ArchiveAuditTables] ( + @RetentionMonths INT OUTPUT +) +AS +BEGIN + SET +NOCOUNT ON; + + -- Declare variables + DECLARE +@SourceDB NVARCHAR(128) = DB_NAME(), + @DestDB NVARCHAR(128) = 'labkey_audit', + @SchemaName NVARCHAR(128) = 'audit'; + + SET +@RetentionMonths = CASE WHEN @RetentionMonths - 6 > 12 THEN @RetentionMonths - 6 ELSE 12 +END; + PRINT +N'Archiving audit logs older than ' + CAST(@RetentionMonths AS NVARCHAR(3)) + N' months old' + + DECLARE +@CutoffDate DATETIME = DATEADD(MONTH, -@RetentionMonths, GETDATE()); + + + -- Validate if source database exists + IF +NOT EXISTS (SELECT 1 FROM sys.databases WHERE NAME = @SourceDB) +BEGIN + RAISERROR +('Source database "%s" does not exist.', 16, 1, @SourceDB); + RETURN; +END + + -- Validate if destination database exists + IF +NOT EXISTS (SELECT 1 FROM sys.databases WHERE NAME = @DestDB) +BEGIN + RAISERROR +('Destination database "%s" does not exist.', 16, 1, @DestDB); + RETURN; +END + + -- Create ArchiveAuditLog table if not exists (useful for testing) + DECLARE +@CreateLogTableSQL NVARCHAR(MAX) = ' + IF NOT EXISTS (SELECT 1 FROM ' + QUOTENAME(@DestDB) + '.INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = ''dbo'' AND TABLE_NAME = ''ArchiveAuditLog'') + BEGIN + EXEC(''USE ' + QUOTENAME(@DestDB) + '; + CREATE TABLE dbo.ArchiveAuditLog ( + LogID INT IDENTITY(1,1) NOT NULL, + TableName NVARCHAR(128) NOT NULL, + Operation NVARCHAR(50) NOT NULL, + StartTime DATETIME NOT NULL, + EndTime DATETIME NULL, + Status NVARCHAR(50) NULL, + RecordsProcessed INT NULL, + ErrorMessage NVARCHAR(MAX) NULL, + RetentionMonths INT NULL, + CONSTRAINT PK_ArchiveAuditLog PRIMARY KEY (LogID) + )''); + END'; + +EXEC sp_executesql @CreateLogTableSQL; + + -- Create RetentionMonths column in ArchiveAuditLog table if not exist + DECLARE +@CreateRetentionColumnSQL NVARCHAR(MAX) = ' + IF NOT EXISTS (SELECT 1 FROM ' + QUOTENAME(@DestDB) + '.INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = ''dbo'' + AND TABLE_NAME = ''ArchiveAuditLog'' + AND COLUMN_NAME = ''RetentionMonths'') + BEGIN + EXEC(''USE ' + QUOTENAME(@DestDB) + '; + ALTER TABLE dbo.ArchiveAuditLog + ADD RetentionMonths INT NULL + ''); + END'; + +EXEC sp_executesql @CreateRetentionColumnSQL; + + -- Validate if source schema exists + DECLARE +@SourceSchemaCheck NVARCHAR(MAX) = ' + IF NOT EXISTS (SELECT 1 FROM ' + QUOTENAME(@SourceDB) + '.sys.schemas WHERE name = ''' + @SchemaName + ''') + BEGIN + RAISERROR(''Source schema "%s" does not exist'', 16, 1, ''' + @SchemaName + '''); + END'; + +EXEC sp_executesql @SourceSchemaCheck; + + -- Create destination schema if not exists + DECLARE +@CreateDestSchemaSQL NVARCHAR(MAX) = ' + IF NOT EXISTS (SELECT 1 FROM ' + QUOTENAME(@DestDB) + '.sys.schemas WHERE name = ''' + @SchemaName + ''') + BEGIN + EXEC ' + QUOTENAME(@DestDB) + '.sys.sp_executesql N''CREATE SCHEMA ' + QUOTENAME(@SchemaName) + '''; + END'; + +EXEC sp_executesql @CreateDestSchemaSQL; + + -- Get list of tables to process +CREATE TABLE #TableList +( + TableName NVARCHAR(128) +); + +DECLARE +@GetTablesSQL NVARCHAR(MAX) = ' + INSERT INTO #TableList + SELECT TABLE_NAME + FROM ' + QUOTENAME(@SourceDB) + '.INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = ''' + @SchemaName + ''' + AND TABLE_NAME NOT IN (''c3d330_userauditdomain'', ''c3d317_groupauditdomain'')'; + +EXEC sp_executesql @GetTablesSQL; + + DECLARE +@CurrentTable NVARCHAR(128); + DECLARE +TableCursor CURSOR LOCAL FAST_FORWARD FOR +SELECT TableName FROM #TableList; + +OPEN TableCursor; +FETCH NEXT FROM TableCursor INTO @CurrentTable; + +WHILE +@@FETCH_STATUS = 0 +BEGIN + DECLARE +@LogID INT; + + -- Log the start of archiving for current table + DECLARE +@InsertLogSQL NVARCHAR(MAX) = ' + USE ' + QUOTENAME(@DestDB) + '; + INSERT INTO dbo.ArchiveAuditLog + (TableName, Operation, StartTime, Status, RetentionMonths) + VALUES (''' + @CurrentTable + ''', ''Archive'', GETDATE(), ''Started'', ' + CAST(@RetentionMonths AS NVARCHAR(10)) + '); + SELECT @LogIDOUT = SCOPE_IDENTITY();'; + +EXEC sp_executesql @InsertLogSQL, N'@LogIDOUT INT OUTPUT', @LogIDOUT = @LogID OUTPUT; + +BEGIN TRY + DECLARE +@FullSourceTable NVARCHAR(512) = QUOTENAME(@SourceDB) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@CurrentTable), + @FullDestTable NVARCHAR(512) = QUOTENAME(@DestDB) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@CurrentTable), + @ColumnList NVARCHAR(MAX) = ''; + + -- Create destination table if it doesn't exist + DECLARE +@CheckTableSQL NVARCHAR(MAX) = ' + IF NOT EXISTS (SELECT 1 FROM ' + QUOTENAME(@DestDB) + '.INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = ''' + @SchemaName + ''' + AND TABLE_NAME = ''' + @CurrentTable + ''') + BEGIN + SELECT * INTO ' + @FullDestTable + ' + FROM ' + @FullSourceTable + ' + WHERE 1 = 0; + END'; + +EXEC sp_executesql @CheckTableSQL; + + -- Get column list (excluding identity columns) +CREATE TABLE #Columns +( + ColumnName NVARCHAR(128), + IsIdentity BIT +); + +DECLARE +@GetColumnsSQL NVARCHAR(MAX) = ' + INSERT INTO #Columns + SELECT c.name AS ColumnName, + COLUMNPROPERTY(OBJECT_ID(''' + @FullSourceTable + '''), c.name, ''IsIdentity'') AS IsIdentity + FROM ' + QUOTENAME(@SourceDB) + '.sys.columns c + JOIN ' + QUOTENAME(@SourceDB) + '.sys.tables t ON c.object_id = t.object_id + JOIN ' + QUOTENAME(@SourceDB) + '.sys.schemas s ON t.schema_id = s.schema_id + WHERE s.name = ''' + @SchemaName + ''' + AND t.name = ''' + @CurrentTable + ''''; + +EXEC sp_executesql @GetColumnsSQL; + +SELECT @ColumnList = STRING_AGG(QUOTENAME(ColumnName), ', ') +FROM #Columns +WHERE IsIdentity = 0; + +DROP TABLE #Columns; + +-- Archive data +BEGIN +TRANSACTION; + + DECLARE +@ArchiveSQL NVARCHAR(MAX) = ' + INSERT INTO ' + @FullDestTable + ' (' + @ColumnList + ') + SELECT ' + @ColumnList + ' + FROM ' + @FullSourceTable + ' + WHERE Created < @CutoffDate; + + DECLARE @RecordsInserted INT = @@ROWCOUNT; + + DELETE FROM ' + @FullSourceTable + ' + WHERE Created < @CutoffDate; + + DECLARE @RecordsDeleted INT = @@ROWCOUNT; + + UPDATE ' + QUOTENAME(@DestDB) + '.dbo.ArchiveAuditLog + SET RecordsProcessed = @RecordsInserted, + EndTime = GETDATE(), + Status = ''Success'' + WHERE LogID = @LogID;'; + +EXEC sp_executesql @ArchiveSQL, + N'@CutoffDate DATETIME, @LogID INT', + @CutoffDate = @CutoffDate, + @LogID = @LogID; + +COMMIT TRANSACTION; +END TRY +BEGIN CATCH +IF @@TRANCOUNT > 0 + ROLLBACK TRANSACTION; + + DECLARE +@ErrorMessage NVARCHAR(4000) = 'Error archiving ' + @CurrentTable + ': ' + ERROR_MESSAGE(); + + DECLARE +@UpdateLogSQL NVARCHAR(MAX) = ' + UPDATE ' + QUOTENAME(@DestDB) + '.dbo.ArchiveAuditLog + SET EndTime = GETDATE(), + Status = ''Error'', + ErrorMessage = @ErrorMessage + WHERE LogID = ' + CAST(@LogID AS NVARCHAR(10)); + +EXEC sp_executesql @UpdateLogSQL, N'@ErrorMessage NVARCHAR(4000)', @ErrorMessage = @ErrorMessage; + + PRINT +@ErrorMessage; +END CATCH + +FETCH NEXT FROM TableCursor INTO @CurrentTable; +END + +CLOSE TableCursor; +DEALLOCATE +TableCursor; + +DROP TABLE #TableList; +END \ 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 9b4e8a75e..2e4c069f5 100644 --- a/onprc_ehr/resources/schemas/onprc_ehr.xml +++ b/onprc_ehr/resources/schemas/onprc_ehr.xml @@ -1315,29 +1315,66 @@ - - - - - - - - + + + + + + + + +
- +
- + - - + + + + + + + +
+ + + + + + + + + + + + + + + + +
+ + + + + + + + + + + +
+ DETAILED @@ -1500,5 +1537,26 @@
+ + + + + + + + +
+ + + + + + + + + +
+ + diff --git a/onprc_ehr/resources/scripts/onprc_ehr/onprc_triggers.js b/onprc_ehr/resources/scripts/onprc_ehr/onprc_triggers.js index 30a298a30..51e4b53e8 100644 --- a/onprc_ehr/resources/scripts/onprc_ehr/onprc_triggers.js +++ b/onprc_ehr/resources/scripts/onprc_ehr/onprc_triggers.js @@ -1064,12 +1064,15 @@ exports.init = function(EHR){ Added Diet to the list by Kollil on 5/14/25. Refer to tkt #12506 5. E-X1380 - Diet Daily (Non-standard), 5LOP (TAD) + + Added Diet to the list by Kollil on 8/5/2026. Refer to tkt #15123 + 6. E-YYY85 - Diet, 5000 Chow */ + if (row.code != 'E-85760' && row.code != 'E-Y7735' && row.code != 'E-X0500' && - row.code != 'E-Y9750' && row.code != 'E-X1380' && !row.enddate) { + row.code != 'E-Y9750' && row.code != 'E-X1380' && row.code != 'E-YYY85' && !row.enddate) { EHR.Server.Utils.addError(scriptErrors, 'enddate', 'Must enter enddate', 'WARN'); } - //Added by Kollil, 9/15/25 /* MPA validation, as per ticket #9669 Add validation code to ensure that MPA is ordered for the correct day: diff --git a/onprc_ehr/resources/web/onprc_ehr/window/AddBehaviorCasesWindow.js b/onprc_ehr/resources/web/onprc_ehr/window/AddBehaviorCasesWindow.js index f8082a0ba..c88f57e97 100644 --- a/onprc_ehr/resources/web/onprc_ehr/window/AddBehaviorCasesWindow.js +++ b/onprc_ehr/resources/web/onprc_ehr/window/AddBehaviorCasesWindow.js @@ -50,7 +50,7 @@ Ext4.define('ONPRC_EHR.window.AddBehaviorCasesWindow', { requiredVersion: 9.1, schemaName: 'study', queryName: 'cases', - sort: 'Id/curLocation/room,Id/curLocation/cage,Id,remark,allProblemCategories', + sort: 'Id/curLocation/room,Id/curLocation/cage,Id,category,remark,allProblemCategories', columns: 'Id,objectid,remark,allProblemCategories', filterArray: casesFilterArray, scope: this, @@ -86,17 +86,31 @@ Ext4.define('ONPRC_EHR.window.AddBehaviorCasesWindow', { } var previousObsMap = {}; + var newobservation = ''; + var tempcaseid = ''; + if (this.obsResults && this.obsResults.rows && this.obsResults.rows.length){ Ext4.Array.forEach(this.obsResults.rows, function(sr){ //reset variable - var newobservation = ''; - var newremark = ''; + var row = new LDK.SelectRowsRow(sr); - newobservation = row.getValue('category'); - newremark = row.getValue('remark'); + //note: this has been changed to ensure 1 row per case var key = row.getValue('caseid'); + // if ( row.getValue('category') == 'Alopecia Regrowth' || (tempcaseid != key || tempcaseid == '') ) { + if ( (tempcaseid != key || tempcaseid == '') ) { + if (row.getValue('category') != 'Alopecia Regrowth') { + newobservation = ''; + tempcaseid = ''; + } + else + { + newobservation = row.getValue('category'); //load Alopecia Regrowth + tempcaseid = row.getValue('caseid'); + } + + } if (!previousObsMap[key]) previousObsMap[key] = []; @@ -110,7 +124,8 @@ Ext4.define('ONPRC_EHR.window.AddBehaviorCasesWindow', { allProblemCategories:row.getValue('allProblemCategories'), remark: row.getValue('remark') }); - if (newobservation == 'Alopecia Score' && (newremark == null || newremark == '')) { + + if (row.getValue('category') == 'Alopecia Score' && (newobservation == '') && tempcaseid == '' && (row.getValue('remark') == null || row.getValue('remark') == '')) { previousObsMap[key].push({ Id: row.getValue('Id'), date: this.recordData.date, @@ -121,7 +136,8 @@ Ext4.define('ONPRC_EHR.window.AddBehaviorCasesWindow', { allProblemCategories:row.getValue('allProblemCategories') }); - + newobservation = ''; + tempcaseid = ''; } }, this); } 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 6e766bdc6..378583262 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRModule.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/ONPRC_EHRModule.java @@ -124,7 +124,7 @@ public String getName() @Override public @Nullable Double getSchemaVersion() { - return 25.005; + return 26.003; } @Override diff --git a/onprc_ehr/src/org/labkey/onprc_ehr/notification/AdminNotifications.java b/onprc_ehr/src/org/labkey/onprc_ehr/notification/AdminNotifications.java index d9fc7fd8e..534ac5cce 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/AdminNotifications.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/AdminNotifications.java @@ -106,13 +106,14 @@ private void MedsEndDateAlert(Container c, User u, final StringBuilder msg, fina "
2. E-Y7735 (Diet - Weekly Multivitamin)" + "
3. E-X0500 (Diet, L-Phyto (Low-phytoestrogen)) " + "
4. E-Y9750 (Diet, 5047 High Protein, Jumbo) " + - "
5. E-X1380 (Diet Daily (Non-standard), 5LOP (TAD))
"); + "
5. E-X1380 (Diet Daily (Non-standard), 5LOP (TAD)) " + + "
6. E-YYY85 (5000 Chow)
"); } else if (count > 0) { //Display the report link on the notification page - msg.append("
" + count + " treatment order(s) found with missing end dates

"); - msg.append("

Click here to view the treatments

\n"); + msg.append("
" + count + " treatment order(s) found with missing end dates. "); + msg.append("Click here to view the Medications/Diets in a grid view\n"); msg.append("
"); //Display the report in the email @@ -134,40 +135,41 @@ else if (count > 0) columns.add(FieldKey.fromString("modifiedby")); columns.add(FieldKey.fromString("modified")); columns.add(FieldKey.fromString("category")); + columns.add(FieldKey.fromString("qcstate")); columns.add(FieldKey.fromString("taskid")); final Map colMap = QueryService.get().getColumns(ti, columns); TableSelector ts2 = new TableSelector(ti, colMap.values(), null, new Sort("date")); // Table header - msg.append(""); - msg.append(""); - msg.append("
"); + + msg.append("
"); msg.append(""); - msg.append(""); + msg.append(""); ts2.forEach(object -> { Results rs = new ResultsImpl(object, colMap); String url = getParticipantURL(c, rs.getString("Id")); - msg.append("\n"); - 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("\n"); + 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("\n"); msg.append(""); }); msg.append("
Id Begin Date End Date Frequency Times Charge To Treatment Volume Concentration Amount Route Ordered By Remark Reason Modified By Modified Date Category Task Id
Id Begin Date End Date Frequency Times Charge To Treatment Volume Concentration Amount Route Ordered By Remark Reason Modified By Modified Date Category QCState Task Id
" + PageFlowUtil.filter(rs.getString("Id")) + "" + PageFlowUtil.filter(rs.getString("date")) + "" + PageFlowUtil.filter(rs.getString("enddate")) + "" + PageFlowUtil.filter(rs.getString("frequency")) + "" + PageFlowUtil.filter(rs.getString("treatmentTimes")) + "" + PageFlowUtil.filter(rs.getString("project")) + "" + PageFlowUtil.filter(rs.getString("code")) + "" + PageFlowUtil.filter(rs.getString("volumewithunits")) + "" + PageFlowUtil.filter(rs.getString("concentrationwithunits")) + "" + PageFlowUtil.filter(rs.getString("amountwithunits")) + "" + PageFlowUtil.filter(rs.getString("route")) + "" + PageFlowUtil.filter(rs.getString("performedby")) + "" + PageFlowUtil.filter(rs.getString("remark")) + "" + PageFlowUtil.filter(rs.getString("reason")) + "" + PageFlowUtil.filter(rs.getString("modifiedby")) + "" + PageFlowUtil.filter(rs.getString("modified")) + "" + PageFlowUtil.filter(rs.getString("category")) + "" + PageFlowUtil.filter(rs.getString("taskid")) + " " + PageFlowUtil.filter(rs.getString("Id")) + " " + PageFlowUtil.filter(rs.getString("date")) + "" + PageFlowUtil.filter(rs.getString("enddate")) + "" + PageFlowUtil.filter(rs.getString("frequency")) + "" + PageFlowUtil.filter(rs.getString("treatmentTimes")) + "" + PageFlowUtil.filter(rs.getString("project")) + "" + PageFlowUtil.filter(rs.getString("code")) + "" + PageFlowUtil.filter(rs.getString("volumewithunits")) + "" + PageFlowUtil.filter(rs.getString("concentrationwithunits")) + "" + PageFlowUtil.filter(rs.getString("amountwithunits")) + "" + PageFlowUtil.filter(rs.getString("route")) + "" + PageFlowUtil.filter(rs.getString("performedby")) + "" + PageFlowUtil.filter(rs.getString("remark")) + "" + PageFlowUtil.filter(rs.getString("reason")) + "" + PageFlowUtil.filter(rs.getString("modifiedby")) + "" + PageFlowUtil.filter(rs.getString("modified")) + "" + PageFlowUtil.filter(rs.getString("category")) + "" + PageFlowUtil.filter(rs.getString("qcstate")) + "" + PageFlowUtil.filter(rs.getString("taskid")) + "
"); 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 e2829e445..aaed5fe1b 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/BehaviorNotification.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/BehaviorNotification.java @@ -351,8 +351,7 @@ private void assignmentsReleasedInPast1Day(final Container c, User u, final Stri final Map colMap = QueryService.get().getColumns(ti, columns); TableSelector ts2 = new TableSelector(ti, colMap.values(), null, new Sort("Id")); -// msg.append("
Assignments with new \"Release date\" added within the last 24hrs:

\n"); - msg.append(""); + msg.append("
"); msg.append(""); msg.append(""); @@ -360,22 +359,22 @@ private void assignmentsReleasedInPast1Day(final Container c, User u, final Stri Results rs = new ResultsImpl(object, colMap); String url = getParticipantURL(c, rs.getString("Id")); - msg.append(""); - msg.append("\n"); - 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("\n"); + 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("
Id Sex Room Cage Project Protocol Title Project Investigator Assign Date Release Date Projected Release Date Assignment Type Assign Condition Projected Release Condition Condition At Release
" + PageFlowUtil.filter(rs.getString("Id")) + " " + PageFlowUtil.filter(rs.getString("Sex")) + "" + PageFlowUtil.filter(rs.getString("Room")) + "" + PageFlowUtil.filter(rs.getString("Cage")) + "" + PageFlowUtil.filter(rs.getString("project")) + "" + PageFlowUtil.filter(rs.getString("Protocol")) + "" + PageFlowUtil.filter(rs.getString("Title")) + "" + PageFlowUtil.filter(rs.getString("ProjectInvestigator")) + "" + PageFlowUtil.filter(rs.getString("AssignDate")) + "" + PageFlowUtil.filter(rs.getString("ReleaseDate")) + "" + PageFlowUtil.filter(rs.getString("ProjectedReleaseDate")) + "" + PageFlowUtil.filter(rs.getString("assignmentType")) + "" + PageFlowUtil.filter(rs.getString("assignCondition")) + "" + PageFlowUtil.filter(rs.getString("projectedReleaseCondition")) + "" + PageFlowUtil.filter(rs.getString("ConditionAtRelease")) + "
" + PageFlowUtil.filter(rs.getString("Id")) + " " + PageFlowUtil.filter(rs.getString("Sex")) + "" + PageFlowUtil.filter(rs.getString("Room")) + "" + PageFlowUtil.filter(rs.getString("Cage")) + "" + PageFlowUtil.filter(rs.getString("project")) + "" + PageFlowUtil.filter(rs.getString("Protocol")) + "" + PageFlowUtil.filter(rs.getString("Title")) + "" + PageFlowUtil.filter(rs.getString("ProjectInvestigator")) + "" + PageFlowUtil.filter(rs.getString("AssignDate")) + "" + PageFlowUtil.filter(rs.getString("ReleaseDate")) + "" + PageFlowUtil.filter(rs.getString("ProjectedReleaseDate")) + "" + PageFlowUtil.filter(rs.getString("assignmentType")) + "" + PageFlowUtil.filter(rs.getString("assignCondition")) + "" + PageFlowUtil.filter(rs.getString("projectedReleaseCondition")) + "" + PageFlowUtil.filter(rs.getString("ConditionAtRelease")) + "


"); @@ -394,17 +393,62 @@ private void AlopeciaScoreAlert(final Container c, User u, final StringBuilder m TableInfo ti = getStudySchema(c, u).getTable("AlopeciaScoreMissingBehaviorCases"); TableSelector ts = new TableSelector(ti, null, null); - long total = ts.getRowCount(); - msg.append("Animals with alopecia score of 4 or 5, but does not have an open behavioral case for alopecia:

"); - if (total > 0) - { - msg.append( total + " entries found. "); - msg.append("Click here to view them\n"); - msg.append("


\n\n"); + long count = ts.getRowCount(); + + //Get num of rows + if (count > 0) { + msg.append("Animals with alopecia score of 4 or 5, but does not have an open behavioral case for alopecia:

"); + msg.append( count + " entries found. "); + msg.append("Click here to view them in a separate window\n"); + msg.append("\n\n"); + + //Changes made byKolli, July 2026, Refer to tkt # 14974 + //Display the daily report in the email + Set columns = new HashSet<>(); + columns.add(FieldKey.fromString("Id")); + columns.add(FieldKey.fromString("species")); + columns.add(FieldKey.fromString("gender")); + columns.add(FieldKey.fromString("ageinYearsRounded")); + columns.add(FieldKey.fromString("area")); + columns.add(FieldKey.fromString("room")); + columns.add(FieldKey.fromString("cage")); + columns.add(FieldKey.fromString("MostRecentAlopeciaScore")); + columns.add(FieldKey.fromString("date")); + columns.add(FieldKey.fromString("performedby")); + + final Map colMap = QueryService.get().getColumns(ti, columns); + TableSelector ts2 = new TableSelector(ti, colMap.values(), null, new Sort("Id")); + + msg.append(""); + msg.append(""); + msg.append(""); + + ts2.forEach(object -> { + Results rs = new ResultsImpl(object, colMap); + String url = getParticipantURL(c, rs.getString("Id")); + + msg.append(""); + msg.append("\n"); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + msg.append(""); + java.sql.Date date = rs.getDate("date"); + msg.append(""); + msg.append(""); + msg.append(""); + }); + msg.append("
Id Species Sex Age(Years, Rounded) Area Room Cage Most Recent Alopecia Score Date Performed By
" + PageFlowUtil.filter(rs.getString("Id")) + " " + PageFlowUtil.filter(rs.getString("Species")) + "" + PageFlowUtil.filter(rs.getString("gender")) + "" + PageFlowUtil.filter(rs.getString("ageinYearsRounded")) + "" + PageFlowUtil.filter(rs.getString("area")) + "" + PageFlowUtil.filter(rs.getString("room")) + "" + PageFlowUtil.filter(rs.getString("cage")) + "" + PageFlowUtil.filter(rs.getString("MostRecentAlopeciaScore")) + "") + .append(PageFlowUtil.filter( + date == null ? "" : new java.text.SimpleDateFormat("MM/dd/yyyy").format(date) + )) + .append("" + PageFlowUtil.filter(rs.getString("performedby")) + "


"); } - else - { - msg.append("WARNING: No animals found with alopecia score of 4 or 5, but does not have an open behavioral case for alopecia!

\n"); + else { + msg.append("WARNING: No animals found with alopecia score of 4 or 5, there fore no open behavioral case(s) for alopecia!

\n"); } } 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 d17eafc0d..8bfe1ecc1 100644 --- a/onprc_ehr/src/org/labkey/onprc_ehr/notification/ColonyAlertsNotification.java +++ b/onprc_ehr/src/org/labkey/onprc_ehr/notification/ColonyAlertsNotification.java @@ -226,7 +226,7 @@ protected void doCandidateChecks(final Container c, User u, final StringBuilder protected void candidatesForLongTime(final Container c, User u, final StringBuilder msg) { SimpleFilter filter = new SimpleFilter(FieldKey.fromString("isActive"), true, CompareType.EQUAL); - filter.addCondition(FieldKey.fromString("daysElapsed"), 30, CompareType.GTE); + filter.addCondition(FieldKey.fromString("daysElapsed"), 180, CompareType.GTE); filter.addCondition(FieldKey.fromString("flag/category"), "Assign Alias", CompareType.EQUAL); filter.addCondition(FieldKey.fromString("flag/value"), ONPRC_EHRManager.AUC_RESERVED, CompareType.NEQ_OR_NULL); @@ -234,7 +234,8 @@ protected void candidatesForLongTime(final Container c, User u, final StringBuil long count = ts.getRowCount(); if (count > 0) { - msg.append("WARNING: There are " + count + " flags for assignment aliases/candidates that have been active for more than 30 days. This may indicate these flags should be ended.
\n"); + //Changed the num of days by Kollil in Aug, 2026. Refer to tkt #15129 + msg.append("WARNING: There are " + count + " flags for assignment aliases/candidates that have been active for more than 180 days. This may indicate these flags should be ended.
\n"); msg.append("

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


\n\n"); } diff --git a/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/AbstractGenericONPRC_EHRTest.java b/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/AbstractGenericONPRC_EHRTest.java index 1b0ccf945..7fbd52ab4 100644 --- a/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/AbstractGenericONPRC_EHRTest.java +++ b/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/AbstractGenericONPRC_EHRTest.java @@ -39,7 +39,6 @@ import org.labkey.test.util.LogMethod; import org.labkey.test.util.PasswordUtil; import org.labkey.test.util.SchemaHelper; -import org.labkey.test.util.SqlserverOnlyTest; import org.labkey.test.util.ehr.EHRClientAPIHelper; import org.labkey.test.util.ext4cmp.Ext4CmpRef; import org.labkey.test.util.ext4cmp.Ext4ComboRef; @@ -60,7 +59,7 @@ import static org.junit.Assert.assertTrue; -public abstract class AbstractGenericONPRC_EHRTest extends AbstractGenericEHRTest implements SqlserverOnlyTest +public abstract class AbstractGenericONPRC_EHRTest extends AbstractGenericEHRTest { protected static final String REFERENCE_STUDY_PATH = "/resources/referenceStudy"; protected static final String GENETICS_PIPELINE_LOG_PATH = REFERENCE_STUDY_PATH + "/kinship/EHR Kinship Calculation/kinship.txt.log"; diff --git a/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/ONPRC_BillingTest.java b/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/ONPRC_BillingTest.java index 2d2c2eecc..2adf3d9af 100644 --- a/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/ONPRC_BillingTest.java +++ b/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/ONPRC_BillingTest.java @@ -36,6 +36,7 @@ import org.labkey.test.util.Ext4Helper; import org.labkey.test.util.LogMethod; import org.labkey.test.util.PortalHelper; +import org.labkey.test.util.SqlserverOnlyTest; import org.labkey.test.util.ext4cmp.Ext4FieldRef; import org.labkey.test.util.ext4cmp.Ext4GridRef; @@ -53,9 +54,28 @@ import static org.labkey.test.util.Ext4Helper.TextMatchTechnique.CONTAINS; +/** + * NOTE: onprc_billing and sla both declare "SupportedDatabases: mssql, pgsql", but this test — the only one that + * exercises billing behaviour — is still SQL Server only, so that PostgreSQL claim is not verified by CI. + *

+ * The gap is narrower than "no PostgreSQL coverage", and the distinction matters. AbstractGenericONPRC_EHRTest + * enables ONPRC_Billing and SLA and builds linked schemas over both, and it does run on PostgreSQL. So the + * bootstrap scripts execute and the schemas get created under CI on PostgreSQL. What is never exercised is the + * body of any stored routine: plpgsql does not resolve table or column references until a routine is first + * called, so a routine that CI creates successfully can still be entirely broken. + *

+ * That is precisely how a batch of PostgreSQL defects reached review in the 26.3 migration — wrong identifier + * quoting, an int/varchar join, plpgsql variable/column ambiguity, a call to a function that does not exist, and + * routines declared as PROCEDURE that LabKey's ETL layer cannot invoke at all. Every one sat inside a routine + * body that CI created and never called. + *

+ * A cheap first step would be a PostgreSQL test that merely invokes each onprc_billing and sla routine once; + * that alone would have caught most of the above. Removing SqlserverOnlyTest here is the fuller fix, but this + * test has never been run against PostgreSQL and should not be enabled without a green run first. + */ @Category({EHR.class, ONPRC.class}) @BaseWebDriverTest.ClassTimeout(minutes = 20) -public class ONPRC_BillingTest extends AbstractONPRC_EHRTest +public class ONPRC_BillingTest extends AbstractONPRC_EHRTest implements SqlserverOnlyTest { protected static String PROJECT_NAME = "ONPRC_Billing_TestProject"; private static final String BILLING_FOLDER_PATH = "/" + PROJECT_NAME + "/" + BILLING_FOLDER; diff --git a/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/ONPRC_RestrictedIssueTest.java b/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/ONPRC_RestrictedIssueTest.java index 05a537821..3bb33ad01 100644 --- a/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/ONPRC_RestrictedIssueTest.java +++ b/onprc_ehr/test/src/org/labkey/test/tests/onprc_ehr/ONPRC_RestrictedIssueTest.java @@ -15,7 +15,6 @@ import org.labkey.test.pages.search.SearchResultsPage; import org.labkey.test.util.IssuesHelper; import org.labkey.test.util.SearchHelper; -import org.labkey.test.util.SqlserverOnlyTest; import org.labkey.test.util.TestUser; import java.util.Arrays; @@ -26,7 +25,7 @@ import static org.labkey.test.util.PermissionsHelper.FOLDER_ADMIN_ROLE; @Category({EHR.class, ONPRC.class}) -public class ONPRC_RestrictedIssueTest extends BaseWebDriverTest implements SqlserverOnlyTest +public class ONPRC_RestrictedIssueTest extends BaseWebDriverTest { private final IssuesHelper _issuesHelper; diff --git a/sla/module.properties b/sla/module.properties index 3ca9eca66..d52bd8748 100644 --- a/sla/module.properties +++ b/sla/module.properties @@ -1,3 +1,3 @@ ModuleClass: org.labkey.sla.SLAModule -SupportedDatabases: mssql -ManageVersion: false +SupportedDatabases: mssql, pgsql +ManageVersion: true diff --git a/sla/resources/schemas/dbscripts/postgresql/sla-0.000-25.000.sql b/sla/resources/schemas/dbscripts/postgresql/sla-0.000-25.000.sql new file mode 100644 index 000000000..164062bb0 --- /dev/null +++ b/sla/resources/schemas/dbscripts/postgresql/sla-0.000-25.000.sql @@ -0,0 +1,680 @@ +/* + * 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 schema, tables, indexes, and constraints used for SLA module here +-- All SQL VIEW definitions should be created in sla-create.sql and dropped in sla-drop.sql +CREATE SCHEMA sla; + +CREATE TABLE sla.census +( + RowID SERIAL NOT NULL, + Project INTEGER, + CountDate TIMESTAMP, + InvestigatorId INTEGER, + Room VARCHAR(255), + Species VARCHAR(255), + CageType VARCHAR(255), + CageSize VARCHAR(255), + CountType INTEGER, + AnimalCount INTEGER, + CageCount INTEGER, + DLAMInventory INTEGER, + objectid ENTITYID, + + Container ENTITYID NOT NULL, + CreatedBy USERID, + Created TIMESTAMP, + ModifiedBy USERID, + Modified TIMESTAMP, + + CONSTRAINT PK_census PRIMARY KEY (rowId) +); + +CREATE TABLE sla.etl_runs +( + RowId SERIAL, + date TIMESTAMP, + queryname VARCHAR(200), + rowversion VARCHAR(200), + + Container ENTITYID NOT NULL, + + CONSTRAINT PK_etl_runs PRIMARY KEY (rowId) +); + +CREATE TABLE sla.purchase( + RowID SERIAL NOT NULL, + Project INTEGER, + UserID INTEGER, + PriInvPhone VARCHAR(255), + PriInvEmail VARCHAR(255), + RequestorID INTEGER, + VendorID INTEGER, + Username VARCHAR(255), + OHSUAlias VARCHAR(255), + HazardousAgentsUsed INTEGER, + HazardsList VARCHAR(255), + DOBRequired INTEGER, + AdditionalVendorInfo VARCHAR(255), + OtherVendor VARCHAR(255), + VendorContact VARCHAR(255), + ConfirmationNum VARCHAR(255), + HousingConfirmed INTEGER, + IACUCConfirmed INTEGER, + RequestDate TIMESTAMP, + OrderDate TIMESTAMP, + AdminComments VARCHAR(500), + DARComments VARCHAR(500), + OrderedBy VARCHAR(255), + ProjFundingSource VARCHAR(255), + objectid ENTITYID, + + Container ENTITYID, + CreatedBy USERID, + Created TIMESTAMP, + ModifiedBy USERID, + Modified TIMESTAMP, + + CONSTRAINT PK_purchase PRIMARY KEY (rowId) +); + +CREATE TABLE sla.purchaseDetails( + RowId SERIAL NOT NULL, + PurchaseID INTEGER, + Species INTEGER, + Age VARCHAR(255), + Weight VARCHAR(255), + Gestation VARCHAR(255), + Sex INTEGER, + Strain VARCHAR(255), + CageID INTEGER, + NumAnimalsOrdered INTEGER, + NumAnimalsReceived INTEGER, + BoxesQuantity INTEGER, + CostPerAnimal VARCHAR(255), + ShippingCost VARCHAR(255), + TotalCost VARCHAR(255), + HousingInstructions VARCHAR(255), + RequestedArrivalDate TIMESTAMP, + ExpectedArrivalDate TIMESTAMP, + ReceivedDate TIMESTAMP, + ReceivedBy VARCHAR(255), + CancelledBy VARCHAR(255), + DateCancelled TIMESTAMP, + objectid ENTITYID, + + Container ENTITYID, + CreatedBy USERID, + Created TIMESTAMP, + ModifiedBy USERID, + Modified TIMESTAMP, + + CONSTRAINT PK_purchaseDetails PRIMARY KEY (rowId) +); + +CREATE TABLE sla.requestors( + RowId SERIAL NOT NULL, + RequestorId INTEGER, + LastName VARCHAR(255), + FirstName VARCHAR(255), + Initials VARCHAR(10), + PhoneNumber VARCHAR(20), + EmailAddress VARCHAR(255), + objectid ENTITYID, + + Container ENTITYID, + CreatedBy USERID, + Created TIMESTAMP, + ModifiedBy USERID, + Modified TIMESTAMP, + + CONSTRAINT PK_requestors PRIMARY KEY (rowId) +); + +CREATE TABLE sla.vendors( + RowId SERIAL NOT NULL, + SLAVendorName VARCHAR(255), + Phone1 VARCHAR(15), + Phone2 VARCHAR(15), + FundingSourceRequired INTEGER, + Comments VARCHAR(255), + objectid ENTITYID, + + Container ENTITYID, + CreatedBy USERID, + Created TIMESTAMP, + ModifiedBy USERID, + Modified TIMESTAMP, + + CONSTRAINT PK_vendors PRIMARY KEY (rowId) +); + +CREATE TABLE sla.emailList( + RowId SERIAL NOT NULL, + Name VARCHAR(100), + Email VARCHAR(100), + PrimaryNotifier INTEGER, + objectid ENTITYID, + + Container ENTITYID, + CreatedBy USERID, + Created TIMESTAMP, + ModifiedBy USERID, + Modified TIMESTAMP, + + CONSTRAINT PK_emailList PRIMARY KEY (rowId) +); + +/* 13.xxx SQL scripts */ + +--it is easier to drop/recreate, rather than try incremental changes: +SELECT core.fn_dropifexists('census', 'sla', 'TABLE', NULL); +SELECT core.fn_dropifexists('etl_runs', 'sla', 'TABLE', NULL); +SELECT core.fn_dropifexists('purchase', 'sla', 'TABLE', NULL); +SELECT core.fn_dropifexists('purchaseDetails', 'sla', 'TABLE', NULL); +SELECT core.fn_dropifexists('requestors', 'sla', 'TABLE', NULL); +SELECT core.fn_dropifexists('vendors', 'sla', 'TABLE', NULL); +SELECT core.fn_dropifexists('emailList', 'sla', 'TABLE', NULL); + +SELECT core.fn_dropifexists('*', 'sla', 'schema', NULL); + +CREATE SCHEMA sla; + +CREATE TABLE sla.census ( + rowid SERIAL NOT NULL, + project INTEGER, + date TIMESTAMP, + investigatorid ENTITYID, --onprc_ehr.investigators + room VARCHAR(255), + species VARCHAR(255), + cagetype VARCHAR(255), + cagesize VARCHAR(255), + counttype INTEGER, + animalcount INTEGER, + cagecount INTEGER, + dlaminventory INTEGER, + objectid ENTITYID, + + container ENTITYID NOT NULL, + createdby USERID, + created TIMESTAMP, + modifiedby USERID, + modified TIMESTAMP, + + CONSTRAINT PK_census PRIMARY KEY (rowid) +); + +CREATE TABLE sla.etl_runs ( + rowid SERIAL, + date TIMESTAMP, + queryname VARCHAR(200), + rowversion VARCHAR(200), + + container ENTITYID NOT NULL, + + CONSTRAINT PK_etl_runs PRIMARY KEY (rowid) +); + +CREATE TABLE sla.purchase ( + rowid SERIAL NOT NULL, --not the PK + project INTEGER, + account VARCHAR(255), + requestorid ENTITYID, + vendorid ENTITYID, + + hazardslist VARCHAR(255), + dobrequired INTEGER, + comments VARCHAR(4000), + confirmationnum VARCHAR(255), + housingconfirmed INTEGER, + iacucconfirmed INTEGER, + requestdate TIMESTAMP, + orderdate TIMESTAMP, + orderedby VARCHAR(100), + objectid ENTITYID, + + container ENTITYID, + createdby USERID, + created TIMESTAMP, + modifiedby USERID, + modified TIMESTAMP, + + CONSTRAINT PK_purchase PRIMARY KEY (objectid) +); + +CREATE TABLE sla.purchaseDetails ( + rowid SERIAL NOT NULL, + purchaseid ENTITYID, + species INTEGER, + age DOUBLE PRECISION, + weight DOUBLE PRECISION, + weight_units VARCHAR(100), + gestation VARCHAR(255), + gender VARCHAR(100), + strain VARCHAR(255), + cageid INTEGER, + animalsordered INTEGER, + animalsreceived INTEGER, + boxesquantity INTEGER, + costperanimal VARCHAR(255), + shippingcost VARCHAR(255), + totalcost VARCHAR(255), + housingInstructions VARCHAR(255), + requestedarrivaldate TIMESTAMP, + expectedarrivaldate TIMESTAMP, + receiveddate TIMESTAMP, + receivedby VARCHAR(255), + cancelledby VARCHAR(255), + datecancelled TIMESTAMP, + objectid ENTITYID, + + container ENTITYID, + createdby USERID, + created TIMESTAMP, + modifiedby USERID, + modified TIMESTAMP, + + CONSTRAINT PK_purchaseDetails PRIMARY KEY (objectid) +); + +CREATE TABLE sla.requestors ( + rowid SERIAL NOT NULL, --not the PK + lastname VARCHAR(255), + firstname VARCHAR(255), + initials VARCHAR(10), + phone VARCHAR(20), + email VARCHAR(255), + userid USERID, + objectid ENTITYID NOT NULL, + + container ENTITYID, + createdby USERID, + created TIMESTAMP, + modifiedby USERID, + modified TIMESTAMP, + + CONSTRAINT PK_requestors PRIMARY KEY (objectid) +); + +CREATE TABLE sla.vendors ( + rowid SERIAL NOT NULL, --not the PK + name VARCHAR(255), + phone1 VARCHAR(15), + phone2 VARCHAR(15), + fundingSourceRequired INTEGER, + comments VARCHAR(255), + objectid ENTITYID NOT NULL, + + container ENTITYID, + createdby USERID, + created TIMESTAMP, + modifiedby USERID, + modified TIMESTAMP, + + CONSTRAINT PK_vendors PRIMARY KEY (objectid) +); + +ALTER TABLE sla.census DROP CONSTRAINT PK_census; +ALTER TABLE sla.census ALTER COLUMN objectid SET NOT NULL; +ALTER TABLE sla.census DROP COLUMN rowid; + +ALTER TABLE sla.census ADD CONSTRAINT PK_census PRIMARY KEY (objectid); + +CREATE TABLE sla.allowableAnimals ( + protocol VARCHAR(4000), + species VARCHAR(200), + strain VARCHAR(200), + gender VARCHAR(100), + age VARCHAR(100), + allowed INTEGER, + + startdate TIMESTAMP, + enddate TIMESTAMP, + + objectid ENTITYID NOT NULL, + container ENTITYID NOT NULL, + createdby INTEGER NOT NULL, + created TIMESTAMP NOT NULL, + modifiedby INTEGER NOT NULL, + modified TIMESTAMP NOT NULL, + + CONSTRAINT PK_allowableAnimals PRIMARY KEY (objectid) +); + +CREATE TABLE sla.species ( + species VARCHAR(200), + + datedisabled TIMESTAMP, + createdby INTEGER, + created TIMESTAMP, + modifiedby INTEGER, + modified TIMESTAMP, + + CONSTRAINT PK_species PRIMARY KEY (species) +); + +INSERT INTO sla.species (species) VALUES ('Rats'); +INSERT INTO sla.species (species) VALUES ('Hamsters'); +INSERT INTO sla.species (species) VALUES ('Guinea Pigs'); +INSERT INTO sla.species (species) VALUES ('Mice'); +INSERT INTO sla.species (species) VALUES ('Rabbits'); +INSERT INTO sla.species (species) VALUES ('Frogs'); +INSERT INTO sla.species (species) VALUES ('Birds'); +INSERT INTO sla.species (species) VALUES ('Fish'); + +CREATE TABLE sla.gender ( + gender VARCHAR(200), + + datedisabled TIMESTAMP, + createdby INTEGER, + created TIMESTAMP, + modifiedby INTEGER, + modified TIMESTAMP, + + CONSTRAINT PK_gender PRIMARY KEY (gender) +); + +INSERT INTO sla.gender (gender) VALUES ('Male or Female'); +INSERT INTO sla.gender (gender) VALUES ('Female'); +INSERT INTO sla.gender (gender) VALUES ('Male'); + +ALTER TABLE sla.census ADD taskid ENTITYID; +ALTER TABLE sla.census ADD formSort INTEGER; + +ALTER TABLE sla.census ADD QCState INTEGER; + +-- Adding placeholder protocols table for use in the SLA prototype +-- I expect that this table will have additional columns related to the IACUC protocols. +CREATE TABLE sla.protocols ( + protocol VARCHAR(4000), + account VARCHAR(255), + "grant" VARCHAR(255), + --additional IACUC realted fields expected + + --TODO are the protocols container specific? + --container entityid not null, + + createdby INTEGER NOT NULL, + created TIMESTAMP NOT NULL, + modifiedby INTEGER NOT NULL, + modified TIMESTAMP NOT NULL, + + CONSTRAINT PK_protocols PRIMARY KEY (protocol) +); + +CREATE TABLE sla.Reference_Data ( + rowId SERIAL, + label VARCHAR(250) DEFAULT NULL, + value VARCHAR(255), + columnName VARCHAR(255) NOT NULL, + sort_order INTEGER NULL, + endDate TIMESTAMP DEFAULT NULL, + + CONSTRAINT pk_reference PRIMARY KEY (value) +); + +CREATE TABLE sla.purchaseDrafts ( + rowid SERIAL NOT NULL, + owner USERID NOT NULL, + content TEXT NOT NULL, + + container ENTITYID NOT NULL, + createdby USERID, + created TIMESTAMP, + modifiedby USERID, + modified TIMESTAMP, + + CONSTRAINT PK_purchaseDrafts PRIMARY KEY (rowid) +); + +DROP TABLE sla.purchaseDetails; + +CREATE TABLE sla.purchaseDetails ( + rowid SERIAL NOT NULL, + purchaseid ENTITYID, + species VARCHAR(50), + age VARCHAR(200), + weight VARCHAR(200), + weight_units VARCHAR(100), + gestation VARCHAR(255), + gender VARCHAR(50), + strain VARCHAR(255), + room VARCHAR(255), + animalsordered INTEGER, + animalsreceived INTEGER, + boxesquantity INTEGER, + costperanimal VARCHAR(255), + shippingcost VARCHAR(255), + totalcost VARCHAR(255), + housingInstructions VARCHAR(255), + requestedarrivaldate TIMESTAMP, + expectedarrivaldate TIMESTAMP, + receiveddate TIMESTAMP, + receivedby VARCHAR(255), + cancelledby VARCHAR(255), + datecancelled TIMESTAMP, + objectid ENTITYID, + + container ENTITYID, + createdby USERID, + created TIMESTAMP, + modifiedby USERID, + modified TIMESTAMP, + + CONSTRAINT PK_purchaseDetails PRIMARY KEY (objectid) +); + +ALTER TABLE sla.purchase ADD DARComments VARCHAR(1000); +ALTER TABLE sla.purchase ADD VendorContact VARCHAR(100); + +ALTER TABLE sla.purchaseDetails ADD sla_DOB TIMESTAMP; +ALTER TABLE sla.purchaseDetails ADD vendorLocation VARCHAR(200); + +/* 23.xxx SQL scripts */ + +SELECT core.fn_dropifexists('protocols', 'sla', 'TABLE', NULL); + +-- ================================================================================================= +--Created by Kollil +--These tables and stored proc was created to enter weaning data into SLA tables +--Refer to ticket #11233 +-- ================================================================================================= + +--Drop table if exists +SELECT core.fn_dropifexists('weaning', 'sla', 'TABLE', NULL); +--Drop Stored proc if exists +DROP FUNCTION IF EXISTS onprc_ehr.SLAWeaningDataTransfer(); + +CREATE TABLE sla.weaning ( + rowid SERIAL NOT NULL, + investigator VARCHAR(250), + date TIMESTAMP, -- Pup's DOB + project VARCHAR(200), + vendorLocation VARCHAR(200), + DOB TIMESTAMP, --Dam's DOB + DOM TIMESTAMP, --Date of Mating + species VARCHAR(100), + sex VARCHAR(100), + strain VARCHAR(200), + numAlive INTEGER, + numDead INTEGER, + totalPups INTEGER, + dateofTransfer TIMESTAMP, --The date of transfer into SLA tables + createdBy USERID, + created TIMESTAMP, + modifiedBy USERID, + modified TIMESTAMP, + + CONSTRAINT PK_weaning PRIMARY KEY (rowid) +); + +/****** Object: StoredProcedure sla.SLAWeaningDataTransfer Script Date: 8/24/2024 *****/ +-- ========================================================================================== +-- Author: Lakshmi Kolli +-- Create date: 8/24/2024 +-- Description: Create a stored proc to check for any rodents with age >= 21 days and enter +-- the data into SLA tables +-- ========================================================================================== + +CREATE OR REPLACE FUNCTION onprc_ehr.SLAWeaningDataTransfer() +RETURNS void +LANGUAGE plpgsql +AS $$ +DECLARE + _WCount INTEGER; + _alias VARCHAR(100); + _purchaseId ENTITYID; + _center_project INTEGER; + _center_project2 INTEGER; + _counter INTEGER; + _counter2 INTEGER; + _DOT TIMESTAMP; + _DOT2 TIMESTAMP; + _max_rowid INTEGER; +BEGIN + --Check if any rodents age is 21 days and above and not transferred into SLA tables + SELECT COUNT(*) INTO _WCount + FROM sla.weaning + WHERE numAlive > 0 + AND dateofTransfer IS NULL + AND (CURRENT_DATE - CAST(date AS DATE)) >= 21; + + --Found entries, so, insert those records into SLA.purchase and SLA.purchasedetails tables + IF _WCount > 0 THEN + --Create a local temp table to process the weaning data. + CREATE TEMP TABLE TempWeaning ( + rowid SERIAL NOT NULL, + orig_weaning_rowid INTEGER, + investigator VARCHAR(250), + date TIMESTAMP, + project VARCHAR(200), + vendorLocation VARCHAR(200), + DOB TIMESTAMP, + DOM TIMESTAMP, + species VARCHAR(100), + sex VARCHAR(100), + strain VARCHAR(200), + numAlive INTEGER, + dateofTransfer TIMESTAMP, + created TIMESTAMP + ) ON COMMIT DROP; + + --Move the weaning entries into a temp table + INSERT INTO TempWeaning (orig_weaning_rowid, investigator, date, project, vendorlocation, DOB, DOM, species, sex, strain, numAlive, created) + SELECT rowid, investigator, date, project, vendorlocation, date, DOM, species, + CASE + WHEN lower(sex) = lower('F') THEN 'Female' + WHEN lower(sex) = lower('M') THEN 'Male' + ELSE 'Male or Female' + END AS sex, + strain, numAlive, now() + FROM sla.weaning + WHERE numAlive > 0 + AND dateofTransfer IS NULL + AND (CURRENT_DATE - CAST(date AS DATE)) >= 21; + + --Set the counter seed value and upper bound + SELECT MIN(rowid), MAX(rowid) INTO _counter, _max_rowid FROM TempWeaning; + + WHILE _counter <= _max_rowid + LOOP + /* Requestorid - (Kati Marshall ) - 7B3F1ED1-4CD9-4D9A-AFF4-FE0618D49C4B + Userid - (Kati Marshall) - 1294 + vendor - (ONPRC Weaning - SLA) - E1EE1B64-B7BE-1035-BFC4-5107380AE41E + container - (SLA) - 4831D09C-4169-1034-BAD2-5107380A9819 + created - (onprc-is) - 1003 + */ + + SELECT dateofTransfer INTO _DOT FROM TempWeaning WHERE rowid = _counter; + IF _DOT IS NULL THEN + -- Get projectid, PI and account + SELECT project, account INTO _center_project, _alias + FROM ehr.project + WHERE name = (SELECT project FROM TempWeaning WHERE rowid = _counter); + + _purchaseId := gen_random_uuid()::ENTITYID; + + -- Check if the row is already transferred into the main SLA tables. If DOT is null means the row hasn't been transferred yet. + -- Insert weaning data into sla.purchase table as a pending order + INSERT INTO sla.purchase + (project, account, requestorid, vendorid, hazardslist, dobrequired, comments, confirmationnum, housingconfirmed, + iacucconfirmed, requestdate, orderdate, orderedby, objectid, container, createdby, created, modifiedby, modified, DARComments, VendorContact) + VALUES + (_center_project, _alias, '7B3F1ED1-4CD9-4D9A-AFF4-FE0618D49C4B', 'E1EE1B64-B7BE-1035-BFC4-5107380AE41E', '', 0, '', NULL, NULL, NULL, NULL, NULL, '', _purchaseId, + '4831D09C-4169-1034-BAD2-5107380A9819', 1003, now(), NULL, NULL, '', ''); + + --Insert data into purchasedetails with the newly created purchaseid above + INSERT INTO sla.purchaseDetails + (purchaseid, species, age, weight, weight_units, gestation, gender, strain, room, animalsordered, animalsreceived, boxesquantity, costperanimal, shippingcost, + totalcost, housingInstructions, requestedarrivaldate, expectedarrivaldate, receiveddate, receivedby, cancelledby, datecancelled, + objectid, container, createdby, created, modifiedby, modified, sla_DOB, vendorLocation) + SELECT _purchaseId, species, CAST((CURRENT_DATE - CAST(date AS DATE)) AS VARCHAR) || ' days', '', '', '', sex, strain, '', numAlive, NULL, NULL, '', '', + '', '', date + INTERVAL '21 days', date + INTERVAL '21 days', NULL, '', '', NULL, + gen_random_uuid()::ENTITYID, '4831D09C-4169-1034-BAD2-5107380A9819', 1003, now(), NULL, NULL, date, vendorLocation + FROM TempWeaning WHERE rowid = _counter; + + --Update the sla.weaning row with the date of transfer date set for the transferred weaning row + UPDATE sla.weaning + SET dateofTransfer = now() + WHERE rowid = (SELECT orig_weaning_rowid FROM TempWeaning WHERE rowid = _counter); + + UPDATE TempWeaning + SET dateofTransfer = now() + WHERE rowid = _counter; + + --Find if there are any rows with the same center project. Then create them under the same purchaseId + --set the new counter + _counter2 := _counter + 1; + WHILE _counter2 <= _max_rowid + LOOP + SELECT dateofTransfer INTO _DOT2 FROM TempWeaning WHERE rowid = _counter2; + IF _DOT2 IS NULL THEN + --Get projectid of the next row + SELECT project INTO _center_project2 + FROM ehr.project + WHERE name = (SELECT project FROM TempWeaning WHERE rowid = _counter2); + + --If they are same projects, then use the the same purchaseid when creating the purchase details record + IF (_center_project = _center_project2) THEN + INSERT INTO sla.purchaseDetails + (purchaseid, species, age, weight, weight_units, gestation, gender, strain, room, animalsordered, animalsreceived, boxesquantity, costperanimal, shippingcost, + totalcost, housingInstructions, requestedarrivaldate, expectedarrivaldate, receiveddate, receivedby, cancelledby, datecancelled, + objectid, container, createdby, created, modifiedby, modified, sla_DOB, vendorLocation) + SELECT _purchaseId, species, CAST((CURRENT_DATE - CAST(date AS DATE)) AS VARCHAR) || ' days', '', '', '', sex, strain, '', numAlive, NULL, NULL, '', '', + '', '', date + INTERVAL '21 days', date + INTERVAL '21 days', NULL, '', '', NULL, + gen_random_uuid()::ENTITYID, '4831D09C-4169-1034-BAD2-5107380A9819', 1003, now(), NULL, NULL, date, vendorLocation + FROM TempWeaning WHERE rowid = _counter2; + + UPDATE sla.weaning + SET dateofTransfer = now() + WHERE rowid = (SELECT orig_weaning_rowid FROM TempWeaning WHERE rowid = _counter2); + + UPDATE TempWeaning + SET dateofTransfer = now() + WHERE rowid = _counter2; + END IF; + END IF; + _counter2 := _counter2 + 1; + END LOOP; + + END IF; + _counter := _counter + 1; + END LOOP; + + DROP TABLE IF EXISTS TempWeaning; + END IF; +END; +$$; diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-0.00-13.21.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-0.00-13.21.sql deleted file mode 100644 index bd5f3267e..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-0.00-13.21.sql +++ /dev/null @@ -1,182 +0,0 @@ -/* - * 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 schema, tables, indexes, and constraints used for SLA module here --- All SQL VIEW definitions should be created in sla-create.sql and dropped in sla-drop.sql -CREATE SCHEMA sla; -GO - -CREATE TABLE sla.census -( - RowID INT IDENTITY(1,1) NOT NULL, - Project INTEGER, - CountDate DATETIME, - InvestigatorId INTEGER, - Room VARCHAR(255), - Species VARCHAR(255), - CageType VARCHAR(255), - CageSize VARCHAR(255), - CountType INTEGER, - AnimalCount INTEGER, - CageCount INTEGER, - DLAMInventory INTEGER, - objectid ENTITYID, - - Container ENTITYID NOT NULL, - CreatedBy USERID, - Created DATETIME, - ModifiedBy USERID, - Modified DATETIME, - - CONSTRAINT PK_census PRIMARY KEY (rowId) -); - -CREATE TABLE sla.etl_runs -( - RowId int identity(1,1), - date datetime, - queryname varchar(200), - rowversion varchar(200), - - Container ENTITYID NOT NULL, - - CONSTRAINT PK_etl_runs PRIMARY KEY (rowId) -); - -CREATE TABLE sla.purchase( - RowID INT IDENTITY(1,1)NOT NULL, - Project INTEGER , - UserID INTEGER, - PriInvPhone VARCHAR(255), - PriInvEmail VARCHAR(255), - RequestorID INTEGER, - VendorID INTEGER , - Username VARCHAR(255), - OHSUAlias VARCHAR(255), - HazardousAgentsUsed INTEGER, - HazardsList VARCHAR(255), - DOBRequired INTEGER, - AdditionalVendorInfo VARCHAR(255), - OtherVendor VARCHAR(255), - VendorContact VARCHAR(255), - ConfirmationNum VARCHAR(255), - HousingConfirmed INTEGER, - IACUCConfirmed INTEGER, - RequestDate DATETIME , - OrderDate DATETIME, - AdminComments VARCHAR(500), - DARComments VARCHAR(500), - OrderedBy VARCHAR(255), - ProjFundingSource VARCHAR(255), - objectid ENTITYID, - - Container ENTITYID , - CreatedBy USERID, - Created DATETIME, - ModifiedBy USERID, - Modified DATETIME, - - CONSTRAINT PK_purchase PRIMARY KEY (rowId) - -); - -CREATE TABLE sla.purchaseDetails( - RowId INT IDENTITY(1,1)NOT NULL, - PurchaseID INTEGER , - Species INTEGER , - Age VARCHAR(255) , - Weight VARCHAR(255) , - Gestation VARCHAR(255) , - Sex INTEGER , - Strain VARCHAR(255) , - CageID INTEGER , - NumAnimalsOrdered INTEGER , - NumAnimalsReceived INTEGER , - BoxesQuantity INTEGER , - CostPerAnimal VARCHAR(255) , - ShippingCost VARCHAR(255) , - TotalCost VARCHAR(255) , - HousingInstructions VARCHAR(255) , - RequestedArrivalDate DATETIME , - ExpectedArrivalDate DATETIME , - ReceivedDate DATETIME , - ReceivedBy VARCHAR(255) , - CancelledBy VARCHAR(255) , - DateCancelled DATETIME , - objectid ENTITYID, - - Container ENTITYID , - CreatedBy USERID, - Created DATETIME, - ModifiedBy USERID, - Modified DATETIME, - - CONSTRAINT PK_purchaseDetails PRIMARY KEY (rowId) - ); - -CREATE TABLE sla.requestors( - RowId INT IDENTITY(1,1)NOT NULL, - RequestorId INTEGER, - LastName VARCHAR(255), - FirstName VARCHAR(255), - Initials VARCHAR(10) , - PhoneNumber VARCHAR(20), - EmailAddress VARCHAR(255), - objectid ENTITYID, - - Container ENTITYID , - CreatedBy USERID, - Created DATETIME, - ModifiedBy USERID, - Modified DATETIME, - - CONSTRAINT PK_requestors PRIMARY KEY (rowId) -); - -CREATE TABLE sla.vendors( - RowId INT IDENTITY(1,1)NOT NULL, - SLAVendorName VARCHAR(255) , - Phone1 VARCHAR(15) , - Phone2 VARCHAR(15) , - FundingSourceRequired INTEGER , - Comments VARCHAR(255) , - objectid ENTITYID, - - Container ENTITYID , - CreatedBy USERID, - Created DATETIME, - ModifiedBy USERID, - Modified DATETIME, - - CONSTRAINT PK_vendors PRIMARY KEY (rowId) - -) ; - -CREATE TABLE sla.emailList( - RowId INT IDENTITY(1,1) NOT NULL, - Name VARCHAR(100) , - Email VARCHAR(100) , - PrimaryNotifier INTEGER , - objectid ENTITYID, - - Container ENTITYID , - CreatedBy USERID, - Created DATETIME, - ModifiedBy USERID, - Modified DATETIME, - - CONSTRAINT PK_emailList PRIMARY KEY (rowId) -); \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-0.000-25.000.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-0.000-25.000.sql new file mode 100644 index 000000000..d9a7fa67b --- /dev/null +++ b/sla/resources/schemas/dbscripts/sqlserver/sla-0.000-25.000.sql @@ -0,0 +1,685 @@ +/* + * 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 schema, tables, indexes, and constraints used for SLA module here +-- All SQL VIEW definitions should be created in sla-create.sql and dropped in sla-drop.sql +CREATE SCHEMA sla; +GO + +CREATE TABLE sla.census +( + RowID INT IDENTITY(1,1) NOT NULL, + Project INTEGER, + CountDate DATETIME, + InvestigatorId INTEGER, + Room VARCHAR(255), + Species VARCHAR(255), + CageType VARCHAR(255), + CageSize VARCHAR(255), + CountType INTEGER, + AnimalCount INTEGER, + CageCount INTEGER, + DLAMInventory INTEGER, + objectid ENTITYID, + + Container ENTITYID NOT NULL, + CreatedBy USERID, + Created DATETIME, + ModifiedBy USERID, + Modified DATETIME, + + CONSTRAINT PK_census PRIMARY KEY (rowId) +); + +CREATE TABLE sla.etl_runs +( + RowId int identity(1,1), + date datetime, + queryname varchar(200), + rowversion varchar(200), + + Container ENTITYID NOT NULL, + + CONSTRAINT PK_etl_runs PRIMARY KEY (rowId) +); + +CREATE TABLE sla.purchase( + RowID INT IDENTITY(1,1)NOT NULL, + Project INTEGER , + UserID INTEGER, + PriInvPhone VARCHAR(255), + PriInvEmail VARCHAR(255), + RequestorID INTEGER, + VendorID INTEGER , + Username VARCHAR(255), + OHSUAlias VARCHAR(255), + HazardousAgentsUsed INTEGER, + HazardsList VARCHAR(255), + DOBRequired INTEGER, + AdditionalVendorInfo VARCHAR(255), + OtherVendor VARCHAR(255), + VendorContact VARCHAR(255), + ConfirmationNum VARCHAR(255), + HousingConfirmed INTEGER, + IACUCConfirmed INTEGER, + RequestDate DATETIME , + OrderDate DATETIME, + AdminComments VARCHAR(500), + DARComments VARCHAR(500), + OrderedBy VARCHAR(255), + ProjFundingSource VARCHAR(255), + objectid ENTITYID, + + Container ENTITYID , + CreatedBy USERID, + Created DATETIME, + ModifiedBy USERID, + Modified DATETIME, + + CONSTRAINT PK_purchase PRIMARY KEY (rowId) + +); + +CREATE TABLE sla.purchaseDetails( + RowId INT IDENTITY(1,1)NOT NULL, + PurchaseID INTEGER , + Species INTEGER , + Age VARCHAR(255) , + Weight VARCHAR(255) , + Gestation VARCHAR(255) , + Sex INTEGER , + Strain VARCHAR(255) , + CageID INTEGER , + NumAnimalsOrdered INTEGER , + NumAnimalsReceived INTEGER , + BoxesQuantity INTEGER , + CostPerAnimal VARCHAR(255) , + ShippingCost VARCHAR(255) , + TotalCost VARCHAR(255) , + HousingInstructions VARCHAR(255) , + RequestedArrivalDate DATETIME , + ExpectedArrivalDate DATETIME , + ReceivedDate DATETIME , + ReceivedBy VARCHAR(255) , + CancelledBy VARCHAR(255) , + DateCancelled DATETIME , + objectid ENTITYID, + + Container ENTITYID , + CreatedBy USERID, + Created DATETIME, + ModifiedBy USERID, + Modified DATETIME, + + CONSTRAINT PK_purchaseDetails PRIMARY KEY (rowId) + ); + +CREATE TABLE sla.requestors( + RowId INT IDENTITY(1,1)NOT NULL, + RequestorId INTEGER, + LastName VARCHAR(255), + FirstName VARCHAR(255), + Initials VARCHAR(10) , + PhoneNumber VARCHAR(20), + EmailAddress VARCHAR(255), + objectid ENTITYID, + + Container ENTITYID , + CreatedBy USERID, + Created DATETIME, + ModifiedBy USERID, + Modified DATETIME, + + CONSTRAINT PK_requestors PRIMARY KEY (rowId) +); + +CREATE TABLE sla.vendors( + RowId INT IDENTITY(1,1)NOT NULL, + SLAVendorName VARCHAR(255) , + Phone1 VARCHAR(15) , + Phone2 VARCHAR(15) , + FundingSourceRequired INTEGER , + Comments VARCHAR(255) , + objectid ENTITYID, + + Container ENTITYID , + CreatedBy USERID, + Created DATETIME, + ModifiedBy USERID, + Modified DATETIME, + + CONSTRAINT PK_vendors PRIMARY KEY (rowId) + +) ; + +CREATE TABLE sla.emailList( + RowId INT IDENTITY(1,1) NOT NULL, + Name VARCHAR(100) , + Email VARCHAR(100) , + PrimaryNotifier INTEGER , + objectid ENTITYID, + + Container ENTITYID , + CreatedBy USERID, + Created DATETIME, + ModifiedBy USERID, + Modified DATETIME, + + CONSTRAINT PK_emailList PRIMARY KEY (rowId) +); + +/* 13.xxx SQL scripts */ + +--it is easier to drop/recreate, rather than try incremental changes: +EXEC core.fn_dropifexists 'census', 'sla', 'TABLE', NULL; +EXEC core.fn_dropifexists 'etl_runs', 'sla', 'TABLE', NULL; +EXEC core.fn_dropifexists 'purchase', 'sla', 'TABLE', NULL; +EXEC core.fn_dropifexists 'purchaseDetails', 'sla', 'TABLE', NULL; +EXEC core.fn_dropifexists 'requestors', 'sla', 'TABLE', NULL; +EXEC core.fn_dropifexists 'vendors', 'sla', 'TABLE', NULL; +EXEC core.fn_dropifexists 'emailList', 'sla', 'TABLE', NULL; + +EXEC core.fn_dropifexists '*', 'sla', 'schema', NULL; +GO +CREATE SCHEMA sla; +GO + +CREATE TABLE sla.census ( + rowid INT IDENTITY(1,1) NOT NULL, + project INTEGER, + date DATETIME, + investigatorid ENTITYID, --onprc_ehr.investigators + room VARCHAR(255), + species VARCHAR(255), + cagetype VARCHAR(255), + cagesize VARCHAR(255), + counttype INTEGER, + animalcount INTEGER, + cagecount INTEGER, + dlaminventory INTEGER, + objectid ENTITYID, + + container ENTITYID NOT NULL, + createdby USERID, + created DATETIME, + modifiedby USERID, + modified DATETIME, + + CONSTRAINT PK_census PRIMARY KEY (rowid) +); + +CREATE TABLE sla.etl_runs ( + rowid int identity(1,1), + date datetime, + queryname varchar(200), + rowversion varchar(200), + + container ENTITYID NOT NULL, + + CONSTRAINT PK_etl_runs PRIMARY KEY (rowid) +); + +CREATE TABLE sla.purchase ( + rowid INT IDENTITY(1,1) NOT NULL, --not the PK + project INTEGER, + account VARCHAR(255), + requestorid ENTITYID, + vendorid ENTITYID, + + hazardslist VARCHAR(255), + dobrequired INTEGER, + comments VARCHAR(4000), + confirmationnum VARCHAR(255), + housingconfirmed INTEGER, + iacucconfirmed INTEGER, + requestdate DATETIME, + orderdate DATETIME, + orderedby VARCHAR(100), + objectid ENTITYID, + + container ENTITYID, + createdby USERID, + created DATETIME, + modifiedby USERID, + modified DATETIME, + + CONSTRAINT PK_purchase PRIMARY KEY (objectid) +); + +CREATE TABLE sla.purchaseDetails ( + rowid INT IDENTITY(1,1) NOT NULL, + purchaseid ENTITYID, + species INTEGER, + age double precision, + weight double precision, + weight_units varchar(100), + gestation VARCHAR(255), + gender varchar(100), + strain VARCHAR(255), + cageid INTEGER, + animalsordered INTEGER, + animalsreceived INTEGER, + boxesquantity INTEGER, + costperanimal VARCHAR(255), + shippingcost VARCHAR(255), + totalcost VARCHAR(255), + housingInstructions VARCHAR(255), + requestedarrivaldate DATETIME, + expectedarrivaldate DATETIME, + receiveddate DATETIME, + receivedby VARCHAR(255), + cancelledby VARCHAR(255), + datecancelled DATETIME, + objectid ENTITYID, + + container ENTITYID, + createdby USERID, + created DATETIME, + modifiedby USERID, + modified DATETIME, + + CONSTRAINT PK_purchaseDetails PRIMARY KEY (objectid) + ); + +CREATE TABLE sla.requestors ( + rowid INT IDENTITY(1,1) NOT NULL, --not the PK + lastname VARCHAR(255), + firstname VARCHAR(255), + initials VARCHAR(10), + phone VARCHAR(20), + email VARCHAR(255), + userid USERID, + objectid ENTITYID NOT NULL, + + container ENTITYID, + createdby USERID, + created DATETIME, + modifiedby USERID, + modified DATETIME, + + CONSTRAINT PK_requestors PRIMARY KEY (objectid) +); + +CREATE TABLE sla.vendors ( + rowid INT IDENTITY(1,1) NOT NULL, --not the PK + name VARCHAR(255), + phone1 VARCHAR(15), + phone2 VARCHAR(15), + fundingSourceRequired INTEGER, + comments VARCHAR(255), + objectid ENTITYID NOT NULL, + + container ENTITYID, + createdby USERID, + created DATETIME, + modifiedby USERID, + modified DATETIME, + + CONSTRAINT PK_vendors PRIMARY KEY (objectid) +); + +ALTER TABLE sla.census DROP CONSTRAINT PK_Census; +GO +ALTER TABLE sla.census ALTER COLUMN objectid ENTITYID NOT NULL; +GO +ALTER TABLE sla.census DROP COLUMN rowid; + +ALTER TABLE sla.census ADD CONSTRAINT PK_Census PRIMARY KEY (objectid); + +CREATE TABLE sla.allowableAnimals ( + protocol varchar(4000), + species varchar (200), + strain varchar (200), + gender varchar(100), + age varchar(100), + allowed integer, + + startdate datetime, + enddate datetime, + + objectid entityid not null, + container entityid not null, + createdby integer not null, + created datetime not null, + modifiedby integer not null, + modified datetime not null, + + CONSTRAINT PK_allowableAnimals PRIMARY KEY (objectid) +); + +CREATE TABLE sla.species ( + species varchar (200), + + datedisabled datetime, + createdby integer, + created datetime, + modifiedby integer, + modified datetime, + + CONSTRAINT PK_species PRIMARY KEY (species) +); +GO +INSERT INTO sla.species (species) values ('Rats'); +INSERT INTO sla.species (species) values ('Hamsters'); +INSERT INTO sla.species (species) values ('Guinea Pigs'); +INSERT INTO sla.species (species) values ('Mice'); +INSERT INTO sla.species (species) values ('Rabbits'); +INSERT INTO sla.species (species) values ('Frogs'); +INSERT INTO sla.species (species) values ('Birds'); +INSERT INTO sla.species (species) values ('Fish'); + + +CREATE TABLE sla.gender ( + gender varchar (200), + + datedisabled datetime, + createdby integer, + created datetime, + modifiedby integer, + modified datetime, + + CONSTRAINT PK_gender PRIMARY KEY (gender) +); +GO +INSERT INTO sla.gender (gender) values ('Male or Female'); +INSERT INTO sla.gender (gender) values ('Female'); +INSERT INTO sla.gender (gender) values ('Male'); + +ALTER TABLE sla.census add taskid entityid; +ALTER TABLE sla.census add formSort integer; + +ALTER TABLE sla.census add QCState Integer; + +-- Adding placeholder protocols table for use in the SLA prototype +-- I expect that this table will have additional columns related to the IACUC protocols. +CREATE TABLE sla.protocols ( + protocol varchar(4000), + account varchar(255), + "grant" varchar(255), + --additional IACUC realted fields expected + + --TODO are the protocols container specific? + --container entityid not null, + + createdby integer not null, + created datetime not null, + modifiedby integer not null, + modified datetime not null, + + CONSTRAINT PK_protocols PRIMARY KEY (protocol) +); + +CREATE TABLE sla.Reference_Data ( +rowId int identity(1,1), +label varchar(250) DEFAULT NULL, +value varchar(255) , +columnName varchar(255) NOT NULL, +sort_order integer null, +endDate datetime DEFAULT NULL, + + CONSTRAINT pk_reference PRIMARY KEY (value) +) +; + +GO + +CREATE TABLE sla.purchaseDrafts ( + rowid INT IDENTITY(1,1) NOT NULL, + owner USERID NOT NULL, + content NVARCHAR(MAX) NOT NULL, + + container ENTITYID NOT NULL, + createdby USERID, + created DATETIME, + modifiedby USERID, + modified DATETIME, + + CONSTRAINT PK_purchaseDrafts PRIMARY KEY (rowid) +); + +DROP TABLE sla.purchaseDetails + +CREATE TABLE sla.purchaseDetails ( + rowid INT IDENTITY(1,1) NOT NULL, + purchaseid ENTITYID, + species varchar(50), + age varchar(200), + weight varchar(200), + weight_units varchar(100), + gestation VARCHAR(255), + gender varchar(50), + strain VARCHAR(255), + room varchar(255), + animalsordered INTEGER, + animalsreceived INTEGER, + boxesquantity INTEGER, + costperanimal VARCHAR(255), + shippingcost VARCHAR(255), + totalcost VARCHAR(255), + housingInstructions VARCHAR(255), + requestedarrivaldate DATETIME, + expectedarrivaldate DATETIME, + receiveddate DATETIME, + receivedby VARCHAR(255), + cancelledby VARCHAR(255), + datecancelled DATETIME, + objectid ENTITYID, + + container ENTITYID, + createdby USERID, + created DATETIME, + modifiedby USERID, + modified DATETIME, + + CONSTRAINT PK_purchaseDetails PRIMARY KEY (objectid) + ); + +ALTER TABLE sla.purchase add DARComments VARCHAR(1000); +ALTER TABLE sla.purchase add VendorContact VARCHAR(100); + +ALTER TABLE sla.purchaseDetails add sla_DOB DATETIME; +ALTER TABLE sla.purchaseDetails add vendorLocation VARCHAR(200); + +/* 23.xxx SQL scripts */ + +EXEC core.fn_dropifexists 'protocols', 'sla', 'TABLE', NULL; +GO + +-- ================================================================================================= +--Created by Kollil +--These tables and stored proc was created to enter weaning data into SLA tables +--Refer to ticket #11233 +-- ================================================================================================= + +--Drop table if exists +EXEC core.fn_dropifexists 'weaning','sla','TABLE'; +--Drop Stored proc if exists +EXEC core.fn_dropifexists 'SLAWeaningDataTransfer', 'onprc_ehr', 'PROCEDURE'; +GO + +CREATE TABLE sla.weaning ( + rowid int IDENTITY(1,1) NOT NULL, + investigator varchar(250), + date DATETIME, -- Pup's DOB + project varchar(200), + vendorLocation varchar(200), + DOB DATETIME, --Dam's DOB + DOM DATETIME, --Date of Mating + species varchar(100), + sex varchar(100), + strain varchar (200), + numAlive INTEGER, + numDead INTEGER, + totalPups INTEGER, + dateofTransfer DATETIME, --The date of transfer into SLA tables + createdBy USERID, + created DATETIME, + modifiedBy USERID, + modified DATETIME, + + CONSTRAINT PK_weaning PRIMARY KEY (rowid) +); + +GO + +/****** Object: StoredProcedure sla.SLAWeaningDataTransfer Script Date: 8/24/2024 *****/ +-- ========================================================================================== +-- Author: Lakshmi Kolli +-- Create date: 8/24/2024 +-- Description: Create a stored proc to check for any rodents with age >= 21 days and enter +-- the data into SLA tables +-- ========================================================================================== + +CREATE PROCEDURE [onprc_ehr].[SLAWeaningDataTransfer] +AS + +DECLARE + @WCount int, + @alias varchar(100), + @purchaseId entityid, + @center_project int, + @center_project2 int, + @counter int, + @counter2 int, + @DOT DATETIME, + @DOT2 DATETIME + +BEGIN + --Check if any rodents age is 21 days and above and not transferred into SLA tables + Select @WCount = COUNT(*) From sla.weaning Where numAlive > 0 And dateofTransfer is null And DateDiff(dd, date, GETDATE()) >= 21 + + --Found entries, so, insert those records into SLA.purchase and SLA.purchasedetails tables + If @WCount > 0 -- start if, 1 + Begin + --Create a local temp table to process the weaning data. The table drops automatically at the end of the session + CREATE TABLE #TempWeaning ( + rowid int IDENTITY(1,1) NOT NULL, + orig_weaning_rowid INTEGER, + investigator varchar(250), + date DATETIME, + project varchar(200), + vendorLocation varchar(200), + DOB DATETIME, + DOM DATETIME, + species varchar(100), + sex varchar(100), + strain varchar (200), + numAlive INTEGER, + dateofTransfer DATETIME, + created DATETIME + ); + + --Move the weaning entries into a temp table + INSERT INTO #TempWeaning (orig_weaning_rowid, investigator, date, project, vendorlocation, DOB, DOM, species, sex, strain, numAlive, created) + Select rowid, investigator, date, project, vendorlocation, date, DOM, species, + CASE + WHEN sex = 'F' THEN 'Female' + WHEN sex = 'M' THEN 'Male' + ELSE 'Male or Female' + END AS sex, + strain, numAlive, GETDATE() From sla.weaning Where numAlive > 0 And dateofTransfer is null And DateDiff(dd, date, GETDATE()) >= 21 + + --Set the counter seed value + Select top 1 @counter = rowid from #TempWeaning order by rowid asc + + WHILE @counter <= @WCount -- start 1st while + BEGIN + /* Requestorid - (Kati Marshall ) - 7B3F1ED1-4CD9-4D9A-AFF4-FE0618D49C4B + Userid - (Kati Marshall) - 1294 + vendor - (ONPRC Weaning - SLA) - E1EE1B64-B7BE-1035-BFC4-5107380AE41E + container - (SLA) - 4831D09C-4169-1034-BAD2-5107380A9819 + created - (onprc-is) - 1003 + */ + + Select @DOT = dateofTransfer From #TempWeaning Where rowid = @counter + If @DOT IS NULL --start @DOT + Begin + -- Get projectid, PI and account + Select @center_project = project, @alias = account From ehr.project Where name = (Select project From #TempWeaning Where rowid = @counter) + + -- Check if the row is already transferred into the main SLA tables. If DOT is null means the row hasn't been transferred yet. + --Insert weaning data into sla.purchase table as a pending order + INSERT INTO sla.purchase + (project, account, requestorid, vendorid, hazardslist, dobrequired, comments, confirmationnum, housingconfirmed, + iacucconfirmed, requestdate, orderdate, orderedby, objectid, container, createdby, created, modifiedby, modified, DARComments, VendorContact) + Select @center_project, @alias ,'7B3F1ED1-4CD9-4D9A-AFF4-FE0618D49C4B','E1EE1B64-B7BE-1035-BFC4-5107380AE41E','',0,'',null,null,null,null,null,'',NEWID(), + '4831D09C-4169-1034-BAD2-5107380A9819',1003,GETDATE(),null,null,'','' + + --Get the newly created purchaseid from sla.purchase + Select top 1 @purchaseid = objectid From sla.purchase order by created desc + + --Insert data into purchasedetails with the newly created purchaseid above + INSERT INTO sla.purchaseDetails + (purchaseid, species, age, weight, weight_units, gestation, gender, strain, room, animalsordered, animalsreceived, boxesquantity, costperanimal, shippingcost, + totalcost, housingInstructions, requestedarrivaldate, expectedarrivaldate, receiveddate, receivedby, cancelledby, datecancelled, + objectid, container, createdby, created, modifiedby, modified, sla_DOB, vendorLocation) + Select @purchaseid, species, CONVERT(VARCHAR, DateDiff(dd, date, GETDATE())) + ' days', '','','',sex, strain,'',numAlive,null,null,'','', + '','',DateAdd(dd, 21, date), DateAdd(dd, 21, date),null,'','',null, + NewId(),'4831D09C-4169-1034-BAD2-5107380A9819',1003,GETDATE(),null,null,date,vendorLocation + From #TempWeaning Where rowid = @counter + + --Update the sla.weaning row with the date of transfer date set for the transferred weaning row + Update sla.weaning + Set dateofTransfer = GETDATE() Where rowid = (Select orig_weaning_rowid from #TempWeaning Where rowid = @counter) + + Update #TempWeaning + Set dateofTransfer = GETDATE() Where rowid = @counter + + --Find if there are any rows with the same center project. Then create them under the same purchaseId + --set the new counter + SET @counter2 = @counter + 1; + WHILE @counter2 <= @Wcount -- start 2nd while + BEGIN + Select @DOT2 = dateofTransfer From #TempWeaning Where rowid = @counter2 + If @DOT2 IS NULL + Begin + --Get projectid of the next row + Select @center_project2 = project From ehr.project Where name = (Select project From #TempWeaning Where rowid = @counter2) + + --If they are same projects, then use the the same purchaseid when creating the purchase details record + If (@center_project = @center_project2) -- start if, 2 + Begin + INSERT INTO sla.purchaseDetails + (purchaseid, species, age, weight, weight_units, gestation, gender, strain, room, animalsordered, animalsreceived, boxesquantity, costperanimal, shippingcost, + totalcost, housingInstructions, requestedarrivaldate, expectedarrivaldate, receiveddate, receivedby, cancelledby, datecancelled, + objectid, container, createdby, created, modifiedby, modified, sla_DOB, vendorLocation) + Select @purchaseid, species, CONVERT(VARCHAR, DateDiff(dd, date, GETDATE())) + ' days', '','','',sex, strain, '',numAlive,null,null,'','', + '','',DateAdd(dd, 21, date), DateAdd(dd, 21, date),null,'','',null, + NewId(),'4831D09C-4169-1034-BAD2-5107380A9819',1003,GETDATE(),null,null,date,vendorLocation + From #TempWeaning Where rowid = @counter2 + + Update sla.weaning + Set dateofTransfer = GETDATE() Where rowid = (Select orig_weaning_rowid from #TempWeaning Where rowid = @counter2) + + Update #TempWeaning + Set dateofTransfer = GETDATE() Where rowid = @counter2 + End -- end if, 2 + End --end DOT2 + SET @counter2 = @counter2 + 1; + END -- end, 2nd while + + End --end @DOT + SET @counter = @counter + 1; + END -- end, 1st while + End -- end if, 1 + + --Drop the temp table incase it exists... + IF EXISTS (SELECT * FROM tempdb.sys.tables WHERE name = '#TempWeaning') + BEGIN + DROP TABLE #TempWeaning; + END; +END +Go \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.21-13.22.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.21-13.22.sql deleted file mode 100644 index 4e7ffce4e..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.21-13.22.sql +++ /dev/null @@ -1,163 +0,0 @@ -/* - * 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. - */ - ---it is easier to drop/recreate, rather than try incremental changes: -EXEC core.fn_dropifexists 'census', 'sla', 'TABLE', NULL; -EXEC core.fn_dropifexists 'etl_runs', 'sla', 'TABLE', NULL; -EXEC core.fn_dropifexists 'purchase', 'sla', 'TABLE', NULL; -EXEC core.fn_dropifexists 'purchaseDetails', 'sla', 'TABLE', NULL; -EXEC core.fn_dropifexists 'requestors', 'sla', 'TABLE', NULL; -EXEC core.fn_dropifexists 'vendors', 'sla', 'TABLE', NULL; -EXEC core.fn_dropifexists 'emailList', 'sla', 'TABLE', NULL; - -EXEC core.fn_dropifexists '*', 'sla', 'schema', NULL; -GO -CREATE SCHEMA sla; -GO - -CREATE TABLE sla.census ( - rowid INT IDENTITY(1,1) NOT NULL, - project INTEGER, - date DATETIME, - investigatorid ENTITYID, --onprc_ehr.investigators - room VARCHAR(255), - species VARCHAR(255), - cagetype VARCHAR(255), - cagesize VARCHAR(255), - counttype INTEGER, - animalcount INTEGER, - cagecount INTEGER, - dlaminventory INTEGER, - objectid ENTITYID, - - container ENTITYID NOT NULL, - createdby USERID, - created DATETIME, - modifiedby USERID, - modified DATETIME, - - CONSTRAINT PK_census PRIMARY KEY (rowid) -); - -CREATE TABLE sla.etl_runs ( - rowid int identity(1,1), - date datetime, - queryname varchar(200), - rowversion varchar(200), - - container ENTITYID NOT NULL, - - CONSTRAINT PK_etl_runs PRIMARY KEY (rowid) -); - -CREATE TABLE sla.purchase ( - rowid INT IDENTITY(1,1) NOT NULL, --not the PK - project INTEGER, - account VARCHAR(255), - requestorid ENTITYID, - vendorid ENTITYID, - - hazardslist VARCHAR(255), - dobrequired INTEGER, - comments VARCHAR(4000), - confirmationnum VARCHAR(255), - housingconfirmed INTEGER, - iacucconfirmed INTEGER, - requestdate DATETIME, - orderdate DATETIME, - orderedby VARCHAR(100), - objectid ENTITYID, - - container ENTITYID, - createdby USERID, - created DATETIME, - modifiedby USERID, - modified DATETIME, - - CONSTRAINT PK_purchase PRIMARY KEY (objectid) -); - -CREATE TABLE sla.purchaseDetails ( - rowid INT IDENTITY(1,1) NOT NULL, - purchaseid ENTITYID, - species INTEGER, - age double precision, - weight double precision, - weight_units varchar(100), - gestation VARCHAR(255), - gender varchar(100), - strain VARCHAR(255), - cageid INTEGER, - animalsordered INTEGER, - animalsreceived INTEGER, - boxesquantity INTEGER, - costperanimal VARCHAR(255), - shippingcost VARCHAR(255), - totalcost VARCHAR(255), - housingInstructions VARCHAR(255), - requestedarrivaldate DATETIME, - expectedarrivaldate DATETIME, - receiveddate DATETIME, - receivedby VARCHAR(255), - cancelledby VARCHAR(255), - datecancelled DATETIME, - objectid ENTITYID, - - container ENTITYID, - createdby USERID, - created DATETIME, - modifiedby USERID, - modified DATETIME, - - CONSTRAINT PK_purchaseDetails PRIMARY KEY (objectid) - ); - -CREATE TABLE sla.requestors ( - rowid INT IDENTITY(1,1) NOT NULL, --not the PK - lastname VARCHAR(255), - firstname VARCHAR(255), - initials VARCHAR(10), - phone VARCHAR(20), - email VARCHAR(255), - userid USERID, - objectid ENTITYID NOT NULL, - - container ENTITYID, - createdby USERID, - created DATETIME, - modifiedby USERID, - modified DATETIME, - - CONSTRAINT PK_requestors PRIMARY KEY (objectid) -); - -CREATE TABLE sla.vendors ( - rowid INT IDENTITY(1,1) NOT NULL, --not the PK - name VARCHAR(255), - phone1 VARCHAR(15), - phone2 VARCHAR(15), - fundingSourceRequired INTEGER, - comments VARCHAR(255), - objectid ENTITYID NOT NULL, - - container ENTITYID, - createdby USERID, - created DATETIME, - modifiedby USERID, - modified DATETIME, - - CONSTRAINT PK_vendors PRIMARY KEY (objectid) -); \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.22-13.23.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.22-13.23.sql deleted file mode 100644 index f2768821e..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.22-13.23.sql +++ /dev/null @@ -1,7 +0,0 @@ -ALTER TABLE sla.census DROP CONSTRAINT PK_Census; -GO -ALTER TABLE sla.census ALTER COLUMN objectid ENTITYID NOT NULL; -GO -ALTER TABLE sla.census DROP COLUMN rowid; - -ALTER TABLE sla.census ADD CONSTRAINT PK_Census PRIMARY KEY (objectid); \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.23-13.24.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.23-13.24.sql deleted file mode 100644 index d37936f28..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.23-13.24.sql +++ /dev/null @@ -1,20 +0,0 @@ -CREATE TABLE sla.allowableAnimals ( - protocol varchar(4000), - species varchar (200), - strain varchar (200), - gender varchar(100), - age varchar(100), - allowed integer, - - startdate datetime, - enddate datetime, - - objectid entityid not null, - container entityid not null, - createdby integer not null, - created datetime not null, - modifiedby integer not null, - modified datetime not null, - - CONSTRAINT PK_allowableAnimals PRIMARY KEY (objectid) -); \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.24-13.25.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.24-13.25.sql deleted file mode 100644 index 06923cff6..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.24-13.25.sql +++ /dev/null @@ -1,37 +0,0 @@ -CREATE TABLE sla.species ( - species varchar (200), - - datedisabled datetime, - createdby integer, - created datetime, - modifiedby integer, - modified datetime, - - CONSTRAINT PK_species PRIMARY KEY (species) -); -GO -INSERT INTO sla.species (species) values ('Rats'); -INSERT INTO sla.species (species) values ('Hamsters'); -INSERT INTO sla.species (species) values ('Guinea Pigs'); -INSERT INTO sla.species (species) values ('Mice'); -INSERT INTO sla.species (species) values ('Rabbits'); -INSERT INTO sla.species (species) values ('Frogs'); -INSERT INTO sla.species (species) values ('Birds'); -INSERT INTO sla.species (species) values ('Fish'); - - -CREATE TABLE sla.gender ( - gender varchar (200), - - datedisabled datetime, - createdby integer, - created datetime, - modifiedby integer, - modified datetime, - - CONSTRAINT PK_gender PRIMARY KEY (gender) -); -GO -INSERT INTO sla.gender (gender) values ('Male or Female'); -INSERT INTO sla.gender (gender) values ('Female'); -INSERT INTO sla.gender (gender) values ('Male'); \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.25-13.26.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.25-13.26.sql deleted file mode 100644 index e36a837c6..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.25-13.26.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE sla.census add taskid entityid; -ALTER TABLE sla.census add formSort integer; diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.26-13.27.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.26-13.27.sql deleted file mode 100644 index 381baf41e..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.26-13.27.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE sla.census add QCState Integer; - diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.27-13.28.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.27-13.28.sql deleted file mode 100644 index 6884d3c3e..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.27-13.28.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Adding placeholder protocols table for use in the SLA prototype --- I expect that this table will have additional columns related to the IACUC protocols. -CREATE TABLE sla.protocols ( - protocol varchar(4000), - account varchar(255), - "grant" varchar(255), - --additional IACUC realted fields expected - - --TODO are the protocols container specific? - --container entityid not null, - - createdby integer not null, - created datetime not null, - modifiedby integer not null, - modified datetime not null, - - CONSTRAINT PK_protocols PRIMARY KEY (protocol) -); \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.28-13.29.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.28-13.29.sql deleted file mode 100644 index 5ca67f0c2..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.28-13.29.sql +++ /dev/null @@ -1,14 +0,0 @@ - -CREATE TABLE sla.Reference_Data ( -rowId int identity(1,1), -label varchar(250) DEFAULT NULL, -value varchar(255) , -columnName varchar(255) NOT NULL, -sort_order integer null, -endDate datetime DEFAULT NULL, - - CONSTRAINT pk_reference PRIMARY KEY (value) -) -; - -GO \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.33-13.34.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.33-13.34.sql deleted file mode 100644 index ef8ba1eca..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.33-13.34.sql +++ /dev/null @@ -1,14 +0,0 @@ - -CREATE TABLE sla.purchaseDrafts ( - rowid INT IDENTITY(1,1) NOT NULL, - owner USERID NOT NULL, - content NVARCHAR(MAX) NOT NULL, - - container ENTITYID NOT NULL, - createdby USERID, - created DATETIME, - modifiedby USERID, - modified DATETIME, - - CONSTRAINT PK_purchaseDrafts PRIMARY KEY (rowid) -); \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.34-13.35.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.34-13.35.sql deleted file mode 100644 index 5658f61ba..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.34-13.35.sql +++ /dev/null @@ -1,36 +0,0 @@ -DROP TABLE sla.purchaseDetails - -CREATE TABLE sla.purchaseDetails ( - rowid INT IDENTITY(1,1) NOT NULL, - purchaseid ENTITYID, - species varchar(50), - age varchar(200), - weight varchar(200), - weight_units varchar(100), - gestation VARCHAR(255), - gender varchar(50), - strain VARCHAR(255), - room varchar(255), - animalsordered INTEGER, - animalsreceived INTEGER, - boxesquantity INTEGER, - costperanimal VARCHAR(255), - shippingcost VARCHAR(255), - totalcost VARCHAR(255), - housingInstructions VARCHAR(255), - requestedarrivaldate DATETIME, - expectedarrivaldate DATETIME, - receiveddate DATETIME, - receivedby VARCHAR(255), - cancelledby VARCHAR(255), - datecancelled DATETIME, - objectid ENTITYID, - - container ENTITYID, - createdby USERID, - created DATETIME, - modifiedby USERID, - modified DATETIME, - - CONSTRAINT PK_purchaseDetails PRIMARY KEY (objectid) - ); \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.35-13.36.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.35-13.36.sql deleted file mode 100644 index a9b5a8e81..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.35-13.36.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE sla.purchase add DARComments VARCHAR(1000); -ALTER TABLE sla.purchase add VendorContact VARCHAR(100); \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-13.36-13.37.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-13.36-13.37.sql deleted file mode 100644 index 78746a0cd..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-13.36-13.37.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE sla.purchaseDetails add sla_DOB DATETIME; -ALTER TABLE sla.purchaseDetails add vendorLocation VARCHAR(200); \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-23.001-23.002.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-23.001-23.002.sql deleted file mode 100644 index ac19ff66e..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-23.001-23.002.sql +++ /dev/null @@ -1,2 +0,0 @@ -EXEC core.fn_dropifexists 'protocols', 'sla', 'TABLE', NULL; -GO \ No newline at end of file diff --git a/sla/resources/schemas/dbscripts/sqlserver/sla-23.002-23.003.sql b/sla/resources/schemas/dbscripts/sqlserver/sla-23.002-23.003.sql deleted file mode 100644 index 56a05ddc1..000000000 --- a/sla/resources/schemas/dbscripts/sqlserver/sla-23.002-23.003.sql +++ /dev/null @@ -1,185 +0,0 @@ --- ================================================================================================= ---Created by Kollil ---These tables and stored proc was created to enter weaning data into SLA tables ---Refer to ticket #11233 --- ================================================================================================= - ---Drop table if exists -EXEC core.fn_dropifexists 'weaning','sla','TABLE'; ---Drop Stored proc if exists -EXEC core.fn_dropifexists 'SLAWeaningDataTransfer', 'onprc_ehr', 'PROCEDURE'; -GO - -CREATE TABLE sla.weaning ( - rowid int IDENTITY(1,1) NOT NULL, - investigator varchar(250), - date DATETIME, -- Pup's DOB - project varchar(200), - vendorLocation varchar(200), - DOB DATETIME, --Dam's DOB - DOM DATETIME, --Date of Mating - species varchar(100), - sex varchar(100), - strain varchar (200), - numAlive INTEGER, - numDead INTEGER, - totalPups INTEGER, - dateofTransfer DATETIME, --The date of transfer into SLA tables - createdBy USERID, - created DATETIME, - modifiedBy USERID, - modified DATETIME, - - CONSTRAINT PK_weaning PRIMARY KEY (rowid) -); - -GO - -/****** Object: StoredProcedure sla.SLAWeaningDataTransfer Script Date: 8/24/2024 *****/ --- ========================================================================================== --- Author: Lakshmi Kolli --- Create date: 8/24/2024 --- Description: Create a stored proc to check for any rodents with age >= 21 days and enter --- the data into SLA tables --- ========================================================================================== - -CREATE PROCEDURE [onprc_ehr].[SLAWeaningDataTransfer] -AS - -DECLARE - @WCount int, - @alias varchar(100), - @purchaseId entityid, - @center_project int, - @center_project2 int, - @counter int, - @counter2 int, - @DOT DATETIME, - @DOT2 DATETIME - -BEGIN - --Check if any rodents age is 21 days and above and not transferred into SLA tables - Select @WCount = COUNT(*) From sla.weaning Where numAlive > 0 And dateofTransfer is null And DateDiff(dd, date, GETDATE()) >= 21 - - --Found entries, so, insert those records into SLA.purchase and SLA.purchasedetails tables - If @WCount > 0 -- start if, 1 - Begin - --Create a local temp table to process the weaning data. The table drops automatically at the end of the session - CREATE TABLE #TempWeaning ( - rowid int IDENTITY(1,1) NOT NULL, - orig_weaning_rowid INTEGER, - investigator varchar(250), - date DATETIME, - project varchar(200), - vendorLocation varchar(200), - DOB DATETIME, - DOM DATETIME, - species varchar(100), - sex varchar(100), - strain varchar (200), - numAlive INTEGER, - dateofTransfer DATETIME, - created DATETIME - ); - - --Move the weaning entries into a temp table - INSERT INTO #TempWeaning (orig_weaning_rowid, investigator, date, project, vendorlocation, DOB, DOM, species, sex, strain, numAlive, created) - Select rowid, investigator, date, project, vendorlocation, date, DOM, species, - CASE - WHEN sex = 'F' THEN 'Female' - WHEN sex = 'M' THEN 'Male' - ELSE 'Male or Female' - END AS sex, - strain, numAlive, GETDATE() From sla.weaning Where numAlive > 0 And dateofTransfer is null And DateDiff(dd, date, GETDATE()) >= 21 - - --Set the counter seed value - Select top 1 @counter = rowid from #TempWeaning order by rowid asc - - WHILE @counter <= @WCount -- start 1st while - BEGIN - /* Requestorid - (Kati Marshall ) - 7B3F1ED1-4CD9-4D9A-AFF4-FE0618D49C4B - Userid - (Kati Marshall) - 1294 - vendor - (ONPRC Weaning - SLA) - E1EE1B64-B7BE-1035-BFC4-5107380AE41E - container - (SLA) - 4831D09C-4169-1034-BAD2-5107380A9819 - created - (onprc-is) - 1003 - */ - - Select @DOT = dateofTransfer From #TempWeaning Where rowid = @counter - If @DOT IS NULL --start @DOT - Begin - -- Get projectid, PI and account - Select @center_project = project, @alias = account From ehr.project Where name = (Select project From #TempWeaning Where rowid = @counter) - - -- Check if the row is already transferred into the main SLA tables. If DOT is null means the row hasn't been transferred yet. - --Insert weaning data into sla.purchase table as a pending order - INSERT INTO sla.purchase - (project, account, requestorid, vendorid, hazardslist, dobrequired, comments, confirmationnum, housingconfirmed, - iacucconfirmed, requestdate, orderdate, orderedby, objectid, container, createdby, created, modifiedby, modified, DARComments, VendorContact) - Select @center_project, @alias ,'7B3F1ED1-4CD9-4D9A-AFF4-FE0618D49C4B','E1EE1B64-B7BE-1035-BFC4-5107380AE41E','',0,'',null,null,null,null,null,'',NEWID(), - '4831D09C-4169-1034-BAD2-5107380A9819',1003,GETDATE(),null,null,'','' - - --Get the newly created purchaseid from sla.purchase - Select top 1 @purchaseid = objectid From sla.purchase order by created desc - - --Insert data into purchasedetails with the newly created purchaseid above - INSERT INTO sla.purchaseDetails - (purchaseid, species, age, weight, weight_units, gestation, gender, strain, room, animalsordered, animalsreceived, boxesquantity, costperanimal, shippingcost, - totalcost, housingInstructions, requestedarrivaldate, expectedarrivaldate, receiveddate, receivedby, cancelledby, datecancelled, - objectid, container, createdby, created, modifiedby, modified, sla_DOB, vendorLocation) - Select @purchaseid, species, CONVERT(VARCHAR, DateDiff(dd, date, GETDATE())) + ' days', '','','',sex, strain,'',numAlive,null,null,'','', - '','',DateAdd(dd, 21, date), DateAdd(dd, 21, date),null,'','',null, - NewId(),'4831D09C-4169-1034-BAD2-5107380A9819',1003,GETDATE(),null,null,date,vendorLocation - From #TempWeaning Where rowid = @counter - - --Update the sla.weaning row with the date of transfer date set for the transferred weaning row - Update sla.weaning - Set dateofTransfer = GETDATE() Where rowid = (Select orig_weaning_rowid from #TempWeaning Where rowid = @counter) - - Update #TempWeaning - Set dateofTransfer = GETDATE() Where rowid = @counter - - --Find if there are any rows with the same center project. Then create them under the same purchaseId - --set the new counter - SET @counter2 = @counter + 1; - WHILE @counter2 <= @Wcount -- start 2nd while - BEGIN - Select @DOT2 = dateofTransfer From #TempWeaning Where rowid = @counter2 - If @DOT2 IS NULL - Begin - --Get projectid of the next row - Select @center_project2 = project From ehr.project Where name = (Select project From #TempWeaning Where rowid = @counter2) - - --If they are same projects, then use the the same purchaseid when creating the purchase details record - If (@center_project = @center_project2) -- start if, 2 - Begin - INSERT INTO sla.purchaseDetails - (purchaseid, species, age, weight, weight_units, gestation, gender, strain, room, animalsordered, animalsreceived, boxesquantity, costperanimal, shippingcost, - totalcost, housingInstructions, requestedarrivaldate, expectedarrivaldate, receiveddate, receivedby, cancelledby, datecancelled, - objectid, container, createdby, created, modifiedby, modified, sla_DOB, vendorLocation) - Select @purchaseid, species, CONVERT(VARCHAR, DateDiff(dd, date, GETDATE())) + ' days', '','','',sex, strain, '',numAlive,null,null,'','', - '','',DateAdd(dd, 21, date), DateAdd(dd, 21, date),null,'','',null, - NewId(),'4831D09C-4169-1034-BAD2-5107380A9819',1003,GETDATE(),null,null,date,vendorLocation - From #TempWeaning Where rowid = @counter2 - - Update sla.weaning - Set dateofTransfer = GETDATE() Where rowid = (Select orig_weaning_rowid from #TempWeaning Where rowid = @counter2) - - Update #TempWeaning - Set dateofTransfer = GETDATE() Where rowid = @counter2 - End -- end if, 2 - End --end DOT2 - SET @counter2 = @counter2 + 1; - END -- end, 2nd while - - End --end @DOT - SET @counter = @counter + 1; - END -- end, 1st while - End -- end if, 1 - - --Drop the temp table incase it exists... - IF EXISTS (SELECT * FROM tempdb.sys.tables WHERE name = '#TempWeaning') - BEGIN - DROP TABLE #TempWeaning; - END; -END -Go \ No newline at end of file diff --git a/sla/src/org/labkey/sla/SLAModule.java b/sla/src/org/labkey/sla/SLAModule.java index 51f654a8e..d423bdfa3 100644 --- a/sla/src/org/labkey/sla/SLAModule.java +++ b/sla/src/org/labkey/sla/SLAModule.java @@ -57,13 +57,14 @@ public String getName() @Override public @Nullable Double getSchemaVersion() { - return 23.003; + return 26.000; } @Override - public boolean hasScripts() + public double getEarliestUpgradeVersion() { - return true; + // Allow upgrades from 23.000+ + return 23.000; } @Override