PlotDirector/PlotLine/Sql/200_StoryIntelligenceExceptionReview.sql

247 lines
16 KiB
Transact-SQL

-- Review priority is independent from author decisions. Existing data starts unassessed.
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
SET XACT_ABORT ON;
GO
IF COL_LENGTH('dbo.StoryIntelligenceReviewCandidates','ReviewPriority') IS NULL
ALTER TABLE dbo.StoryIntelligenceReviewCandidates ADD ReviewPriority nvarchar(20) NOT NULL CONSTRAINT DF_ReviewCandidate_Priority DEFAULT N'Unassessed',
AssessmentJson nvarchar(max) NULL;
GO
IF COL_LENGTH('dbo.CharacterKnowledge','SourceReviewKey') IS NULL
ALTER TABLE dbo.CharacterKnowledge ADD SourceReviewKey nvarchar(450) NULL;
GO
IF NOT EXISTS(SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('dbo.CharacterKnowledge') AND name='UX_CharacterKnowledge_ReviewSource')
CREATE UNIQUE INDEX UX_CharacterKnowledge_ReviewSource ON dbo.CharacterKnowledge(SceneID,SourceReviewKey) WHERE SourceReviewKey IS NOT NULL;
GO
-- Preserve normal author editing. Imports are insert-once, including retries after interrupted requests.
CREATE OR ALTER PROCEDURE dbo.CharacterKnowledge_Save
@CharacterKnowledgeID int=NULL,@CharacterID int,@StoryAssetID int=NULL,@PlotThreadID int=NULL,
@SceneID int,@KnowledgeStateID int,@SourceEventID int=NULL,@Description nvarchar(max)=NULL,@SourceReviewKey nvarchar(450)=NULL
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
IF ISNULL(@CharacterKnowledgeID,0)=0
BEGIN
IF @SourceReviewKey IS NOT NULL
SELECT @CharacterKnowledgeID=CharacterKnowledgeID FROM dbo.CharacterKnowledge WITH(UPDLOCK,HOLDLOCK)
WHERE SceneID=@SceneID AND SourceReviewKey=@SourceReviewKey;
IF ISNULL(@CharacterKnowledgeID,0)=0
BEGIN
INSERT dbo.CharacterKnowledge(CharacterID,StoryAssetID,PlotThreadID,SceneID,KnowledgeStateID,SourceEventID,Description,SourceReviewKey)
VALUES(@CharacterID,@StoryAssetID,@PlotThreadID,@SceneID,@KnowledgeStateID,@SourceEventID,@Description,@SourceReviewKey);
SET @CharacterKnowledgeID=CONVERT(int,SCOPE_IDENTITY());
END;
END
ELSE
UPDATE dbo.CharacterKnowledge SET CharacterID=@CharacterID,StoryAssetID=@StoryAssetID,PlotThreadID=@PlotThreadID,
SceneID=@SceneID,KnowledgeStateID=@KnowledgeStateID,SourceEventID=@SourceEventID,Description=@Description,UpdatedDate=SYSUTCDATETIME()
WHERE CharacterKnowledgeID=@CharacterKnowledgeID;
COMMIT;
SELECT @CharacterKnowledgeID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceReview_List @BookID int,@Module nvarchar(40)
AS
BEGIN
SET NOCOUNT ON;
SELECT c.* FROM dbo.StoryIntelligenceReviewCandidates c
JOIN dbo.StoryIntelligenceReviewCandidateGenerations g ON g.ReviewCandidateGenerationID=c.ReviewCandidateGenerationID
WHERE g.BookID=@BookID AND g.Module=@Module AND g.IsCurrent=1 AND g.Status=N'Ready'
ORDER BY c.SortOrder,c.ReviewCandidateID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceReview_Summary @BookID int
AS
BEGIN
SET NOCOUNT ON;
SELECT g.Module,COUNT(c.ReviewCandidateID) IdentifiedCount,
SUM(CASE WHEN c.DecisionStatus=N'AutoAccepted' OR (c.DecisionStatus=N'Reviewed' AND c.DecisionAction IN(N'CreateNew',N'LinkExisting',N'Alias')) THEN 1 ELSE 0 END) TrackedCount,
SUM(CASE WHEN c.DecisionStatus=N'Pending' AND c.ReviewPriority=N'Optional' THEN 1 ELSE 0 END) OptionalCount,
SUM(CASE WHEN c.DecisionStatus=N'Pending' AND c.ReviewPriority=N'Attention' THEN 1 ELSE 0 END) AttentionCount,
SUM(CASE WHEN c.DecisionStatus=N'Pending' AND c.ReviewPriority=N'Unassessed' THEN 1 ELSE 0 END) UnassessedCount,
SUM(CASE WHEN c.DecisionStatus=N'Reviewed' THEN 1 ELSE 0 END) DecidedCount,
COUNT(DISTINCT CASE WHEN g.Module=N'Relationships' THEN
CASE WHEN TRY_CONVERT(int,JSON_VALUE(c.CandidatePayloadJson,'$.characterAID'))>0 AND TRY_CONVERT(int,JSON_VALUE(c.CandidatePayloadJson,'$.characterBID'))>0
THEN CASE WHEN TRY_CONVERT(int,JSON_VALUE(c.CandidatePayloadJson,'$.characterAID'))<TRY_CONVERT(int,JSON_VALUE(c.CandidatePayloadJson,'$.characterBID'))
THEN CONCAT(JSON_VALUE(c.CandidatePayloadJson,'$.characterAID'),N':',JSON_VALUE(c.CandidatePayloadJson,'$.characterBID'))
ELSE CONCAT(JSON_VALUE(c.CandidatePayloadJson,'$.characterBID'),N':',JSON_VALUE(c.CandidatePayloadJson,'$.characterAID')) END
WHEN JSON_VALUE(c.CandidatePayloadJson,'$.characterAName')<JSON_VALUE(c.CandidatePayloadJson,'$.characterBName')
THEN CONCAT(JSON_VALUE(c.CandidatePayloadJson,'$.characterAName'),N'|',JSON_VALUE(c.CandidatePayloadJson,'$.characterBName'))
ELSE CONCAT(JSON_VALUE(c.CandidatePayloadJson,'$.characterBName'),N'|',JSON_VALUE(c.CandidatePayloadJson,'$.characterAName')) END END) PairCount
FROM dbo.StoryIntelligenceReviewCandidateGenerations g
LEFT JOIN dbo.StoryIntelligenceReviewCandidates c ON c.ReviewCandidateGenerationID=g.ReviewCandidateGenerationID
WHERE g.BookID=@BookID AND g.IsCurrent=1 AND g.Status=N'Ready' AND g.Module IN(N'Knowledge',N'Relationships',N'Assets')
GROUP BY g.Module;
END;
GO
-- Classification and canonical acceptance are one transaction. A failed write never advertises tracked intelligence.
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceReview_Assess
@ReviewCandidateID int,@ExpectedGenerationID int,@PayloadJson nvarchar(max),@AssessmentJson nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
DECLARE @Module nvarchar(40),@BookID int,@ProjectID int,@Key nvarchar(450),@Priority nvarchar(20)=JSON_VALUE(@AssessmentJson,'$.priority');
SELECT @Module=c.Module,@BookID=c.BookID,@ProjectID=c.ProjectID,@Key=c.StableKey
FROM dbo.StoryIntelligenceReviewCandidates c WITH(UPDLOCK,HOLDLOCK)
JOIN dbo.StoryIntelligenceReviewCandidateGenerations g ON g.ReviewCandidateGenerationID=c.ReviewCandidateGenerationID
WHERE c.ReviewCandidateID=@ReviewCandidateID AND c.ReviewCandidateGenerationID=@ExpectedGenerationID
AND c.DecisionStatus=N'Pending' AND g.IsCurrent=1 AND g.Status=N'Ready';
IF @Module IS NULL BEGIN COMMIT; RETURN; END;
IF @Priority NOT IN(N'Tracked',N'Optional',N'Attention') OR @Module NOT IN(N'Knowledge',N'Relationships',N'Assets')
THROW 53200,'Invalid review assessment.',1;
IF ISNULL(JSON_VALUE(@PayloadJson,'$.key'),N'')<>@Key THROW 53201,'Review identity changed.',1;
-- Rebuilding a generation must not overturn an earlier author decision, even after batch resume.
DECLARE @PreviousID int;
SELECT TOP(1) @PreviousID=ReviewCandidateID FROM dbo.StoryIntelligenceReviewCandidates
WHERE BookID=@BookID AND Module=@Module AND DecisionStatus<>N'Pending' AND ReviewCandidateID<>@ReviewCandidateID
AND (StableKey=@Key OR (@Module=N'Relationships' AND DecisionStatus=N'Reviewed'
AND ISNULL(TRY_CONVERT(int,JSON_VALUE(CandidatePayloadJson,'$.reviewRulesVersion')),0)<3
AND ((JSON_VALUE(CandidatePayloadJson,'$.characterAName')=JSON_VALUE(@PayloadJson,'$.characterAName') AND JSON_VALUE(CandidatePayloadJson,'$.characterBName')=JSON_VALUE(@PayloadJson,'$.characterBName'))
OR (JSON_VALUE(CandidatePayloadJson,'$.characterAName')=JSON_VALUE(@PayloadJson,'$.characterBName') AND JSON_VALUE(CandidatePayloadJson,'$.characterBName')=JSON_VALUE(@PayloadJson,'$.characterAName')))))
ORDER BY CASE WHEN DecisionStatus=N'Reviewed' THEN 0 ELSE 1 END,ReviewCandidateID DESC;
IF @PreviousID IS NOT NULL
BEGIN
UPDATE c SET DecisionStatus=p.DecisionStatus,DecisionAction=p.DecisionAction,DecisionTargetKey=p.DecisionTargetKey,
DecisionCanonicalID=p.DecisionCanonicalID,ReviewedUtc=p.ReviewedUtc,ReviewPriority=p.ReviewPriority,AssessmentJson=p.AssessmentJson
FROM dbo.StoryIntelligenceReviewCandidates c JOIN dbo.StoryIntelligenceReviewCandidates p ON p.ReviewCandidateID=@PreviousID
WHERE c.ReviewCandidateID=@ReviewCandidateID;
END
ELSE
BEGIN
DECLARE @CanonicalID int,@SceneID int,@CharacterID int,@StateID int,@AssetID int,@Description nvarchar(max);
DECLARE @Results TABLE(ID int);
IF @Priority=N'Tracked'
BEGIN
IF @Module=N'Knowledge'
BEGIN
SELECT TOP(1) @SceneID=TRY_CONVERT(int,JSON_VALUE(value,'$.sceneID')) FROM OPENJSON(@PayloadJson,'$.observations')
ORDER BY TRY_CONVERT(decimal(18,4),JSON_VALUE(value,'$.chapterNumber')),TRY_CONVERT(decimal(18,4),JSON_VALUE(value,'$.sceneNumber')),TRY_CONVERT(int,JSON_VALUE(value,'$.sortOrder'));
SET @CharacterID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.characterID'));
SET @StateID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.knowledgeStateID'));
SET @AssetID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.storyAssetID'));
SET @CanonicalID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.existingKnowledgeID'));
IF NOT EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE s.SceneID=@SceneID AND ch.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND s.IsArchived=0 AND ch.IsArchived=0)
OR NOT EXISTS(SELECT 1 FROM dbo.Characters WHERE CharacterID=@CharacterID AND ProjectID=@ProjectID AND IsArchived=0)
THROW 53202,'Knowledge scope changed.',1;
IF @AssetID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.StoryAssets WHERE StoryAssetID=@AssetID AND ProjectID=@ProjectID AND IsArchived=0)
THROW 53203,'Knowledge asset scope changed.',1;
IF @CanonicalID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.CharacterKnowledge WHERE CharacterKnowledgeID=@CanonicalID AND CharacterID=@CharacterID AND KnowledgeStateID=@StateID AND SceneID=@SceneID)
SET @CanonicalID=NULL;
IF @CanonicalID IS NULL
BEGIN
SELECT @Description=CONCAT(statement,CHAR(10),N'Evidence: ',evidence) FROM OPENJSON(@PayloadJson)
WITH(statement nvarchar(max) '$.knowledgeStatement',evidence nvarchar(max) '$.evidence');
INSERT @Results EXEC dbo.CharacterKnowledge_Save @CharacterID=@CharacterID,@StoryAssetID=@AssetID,@SceneID=@SceneID,@KnowledgeStateID=@StateID,@Description=@Description,@SourceReviewKey=@Key;
SELECT @CanonicalID=ID FROM @Results;
END;
END
ELSE IF @Module=N'Relationships'
BEGIN
DECLARE @A int=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.characterAID')),@B int=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.characterBID')),
@TypeID int=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.relationshipTypeID')),
@Permanent bit=CASE WHEN JSON_VALUE(@PayloadJson,'$.proposalKind')=N'Factual' THEN 1 ELSE 0 END,
@Reciprocal bit=CASE WHEN JSON_VALUE(@PayloadJson,'$.isReciprocal')=N'true' THEN 1 ELSE 0 END,
@Known bit=CASE WHEN JSON_VALUE(@PayloadJson,'$.isKnownToOtherCharacter')=N'true' THEN 1 ELSE 0 END,
@Intensity int=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.intensity'));
SET @SceneID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.firstSceneID'));
SET @StateID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.relationshipStateID'));
SELECT @Description=development FROM OPENJSON(@PayloadJson) WITH(development nvarchar(max) '$.development');
INSERT @Results EXEC dbo.StoryIntelligenceRelationship_AcceptDevelopment @ProjectID=@ProjectID,@BookID=@BookID,@SceneID=@SceneID,@SourceReviewKey=@Key,
@CharacterAID=@A,@CharacterBID=@B,@RelationshipTypeID=@TypeID,@RelationshipStateID=@StateID,@IsPermanent=@Permanent,
@IsReciprocal=@Reciprocal,@IsKnownToOtherCharacter=@Known,@Intensity=@Intensity,@Description=@Description;
SELECT @CanonicalID=ID FROM @Results;
END
ELSE THROW 53204,'Automatic creation is not supported for this module.',1;
IF @CanonicalID IS NULL THROW 53205,'Automatic acceptance did not return a canonical record.',1;
END;
UPDATE dbo.StoryIntelligenceReviewCandidates SET CandidatePayloadJson=@PayloadJson,AssessmentJson=@AssessmentJson,ReviewPriority=@Priority,
Confidence=TRY_CONVERT(decimal(9,6),JSON_VALUE(@PayloadJson,'$.rawConfidence')),
DecisionStatus=CASE WHEN @CanonicalID IS NOT NULL THEN N'AutoAccepted' ELSE DecisionStatus END,
DecisionAction=CASE WHEN @CanonicalID IS NOT NULL THEN N'CreateNew' ELSE DecisionAction END,
DecisionCanonicalID=COALESCE(@CanonicalID,DecisionCanonicalID),UpdatedUtc=SYSUTCDATETIME()
WHERE ReviewCandidateID=@ReviewCandidateID;
END;
UPDATE dbo.StoryIntelligenceReviewCandidateGenerations SET PendingCount=(SELECT COUNT(*) FROM dbo.StoryIntelligenceReviewCandidates
WHERE ReviewCandidateGenerationID=@ExpectedGenerationID AND DecisionStatus=N'Pending'),UpdatedUtc=SYSUTCDATETIME()
WHERE ReviewCandidateGenerationID=@ExpectedGenerationID;
COMMIT;
END;
GO
-- Carry settled observations into new preparation generations so history and decisions stay visible.
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceReviewCandidateGeneration_Begin
@ProjectID int,@BookID int,@Module nvarchar(40),@Source nvarchar(80)=N'SceneIntelligencePreparation'
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
DECLARE @Previous int,@Generation int;
SELECT @Previous=ReviewCandidateGenerationID FROM dbo.StoryIntelligenceReviewCandidateGenerations WITH(UPDLOCK,HOLDLOCK)
WHERE BookID=@BookID AND Module=@Module AND IsCurrent=1;
UPDATE dbo.StoryIntelligenceReviewCandidateGenerations SET IsCurrent=0,UpdatedUtc=SYSUTCDATETIME() WHERE ReviewCandidateGenerationID=@Previous;
INSERT dbo.StoryIntelligenceReviewCandidateGenerations(ProjectID,BookID,Module,Status,Source) VALUES(@ProjectID,@BookID,@Module,N'Preparing',@Source);
SET @Generation=CONVERT(int,SCOPE_IDENTITY());
IF @Module IN(N'Knowledge',N'Relationships',N'Assets')
BEGIN
INSERT dbo.StoryIntelligenceReviewCandidates(ReviewCandidateGenerationID,ProjectID,BookID,Module,StableKey,CandidateType,DisplayName,SortOrder,Confidence,
ExistingCanonicalID,DecisionStatus,DecisionAction,DecisionTargetKey,DecisionCanonicalID,CandidatePayloadJson,ReviewedUtc,ReviewPriority,AssessmentJson)
SELECT @Generation,ProjectID,BookID,Module,StableKey,CandidateType,DisplayName,SortOrder,Confidence,
ExistingCanonicalID,DecisionStatus,DecisionAction,DecisionTargetKey,DecisionCanonicalID,CandidatePayloadJson,ReviewedUtc,ReviewPriority,AssessmentJson
FROM dbo.StoryIntelligenceReviewCandidates WHERE ReviewCandidateGenerationID=@Previous AND DecisionStatus<>N'Pending';
INSERT dbo.StoryIntelligenceReviewCandidateEvidence(ReviewCandidateID,SceneID,EvidenceText,Confidence,SortOrder)
SELECT newRow.ReviewCandidateID,e.SceneID,e.EvidenceText,e.Confidence,e.SortOrder
FROM dbo.StoryIntelligenceReviewCandidateEvidence e JOIN dbo.StoryIntelligenceReviewCandidates oldRow ON oldRow.ReviewCandidateID=e.ReviewCandidateID
JOIN dbo.StoryIntelligenceReviewCandidates newRow ON newRow.ReviewCandidateGenerationID=@Generation AND newRow.StableKey=oldRow.StableKey
WHERE oldRow.ReviewCandidateGenerationID=@Previous;
END;
COMMIT;
SELECT * FROM dbo.StoryIntelligenceReviewCandidateGenerations WHERE ReviewCandidateGenerationID=@Generation;
END;
GO
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceReviewCandidate_Save
@ReviewCandidateGenerationID int,
@ProjectID int,
@BookID int,
@Module nvarchar(40),
@StableKey nvarchar(450),
@CandidateType nvarchar(80) = NULL,
@DisplayName nvarchar(450),
@SortOrder int,
@Confidence decimal(9,4) = NULL,
@ExistingCanonicalID int = NULL,
@CandidatePayloadJson nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
MERGE dbo.StoryIntelligenceReviewCandidates AS target
USING (SELECT @ReviewCandidateGenerationID AS ReviewCandidateGenerationID, @StableKey AS StableKey) AS source
ON target.ReviewCandidateGenerationID = source.ReviewCandidateGenerationID
AND target.StableKey = source.StableKey
WHEN MATCHED AND (target.Module NOT IN(N'Knowledge',N'Relationships',N'Assets') OR target.DecisionStatus=N'Pending') THEN
UPDATE SET CandidateType = @CandidateType,
DisplayName = @DisplayName,
SortOrder = @SortOrder,
Confidence = @Confidence,
ExistingCanonicalID = @ExistingCanonicalID,
CandidatePayloadJson = @CandidatePayloadJson,
UpdatedUtc = SYSUTCDATETIME()
WHEN NOT MATCHED THEN
INSERT (ReviewCandidateGenerationID, ProjectID, BookID, Module, StableKey, CandidateType, DisplayName, SortOrder, Confidence, ExistingCanonicalID, CandidatePayloadJson)
VALUES (@ReviewCandidateGenerationID, @ProjectID, @BookID, @Module, @StableKey, @CandidateType, @DisplayName, @SortOrder, @Confidence, @ExistingCanonicalID, @CandidatePayloadJson);
SELECT *
FROM dbo.StoryIntelligenceReviewCandidates
WHERE ReviewCandidateGenerationID = @ReviewCandidateGenerationID
AND StableKey = @StableKey;
END;
GO