Skip to content

Commit

Permalink
Move to a generic draft table
Browse files Browse the repository at this point in the history
Previously had individual/specific draft tables
  • Loading branch information
kyle1morel committed Nov 26, 2024
1 parent c2073d8 commit 980e56a
Show file tree
Hide file tree
Showing 26 changed files with 295 additions and 241 deletions.
44 changes: 22 additions & 22 deletions app/src/controllers/submission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ import { generateCreateStamps, generateUpdateStamps } from '../db/utils/utils';
import {
activityService,
contactService,
draftService,
emailService,
enquiryService,
submissionService,
submissionDraftService,
permitService
} from '../services';
import { BasicResponse, Initiative } from '../utils/enums/application';
import {
ApplicationStatus,
DraftCode,
IntakeStatus,
NumResidentialUnits,
PermitNeeded,
Expand All @@ -27,15 +28,15 @@ import type { NextFunction, Request, Response } from 'express';
import type {
ChefsFormConfig,
ChefsFormConfigData,
Submission,
ChefsSubmissionExport,
Permit,
CurrentContext,
Draft,
Email,
Permit,
StatisticsFilters,
Submission,
SubmissionIntake,
SubmissionSearchParameters,
CurrentContext,
SubmissionDraft
SubmissionSearchParameters
} from '../types';

const controller = {
Expand Down Expand Up @@ -412,9 +413,9 @@ const controller = {
}
},

deleteDraft: async (req: Request<{ submissionDraftId: string }>, res: Response, next: NextFunction) => {
deleteDraft: async (req: Request<{ draftId: string }>, res: Response, next: NextFunction) => {
try {
const response = await submissionDraftService.deleteDraft(req.params.submissionDraftId);
const response = await draftService.deleteDraft(req.params.draftId);

if (!response) {
return res.status(404).json({ message: 'Submission draft not found' });
Expand All @@ -426,9 +427,9 @@ const controller = {
}
},

getDraft: async (req: Request<{ submissionDraftId: string }>, res: Response, next: NextFunction) => {
getDraft: async (req: Request<{ draftId: string }>, res: Response, next: NextFunction) => {
try {
const response = await submissionDraftService.getDraft(req.params.submissionDraftId);
const response = await draftService.getDraft(req.params.draftId);

if (req.currentAuthorization?.attributes.includes('scope:self')) {
if (response?.createdBy !== getCurrentUsername(req.currentContext)) {
Expand All @@ -444,10 +445,10 @@ const controller = {

getDrafts: async (req: Request, res: Response, next: NextFunction) => {
try {
let response = await submissionDraftService.getDrafts();
let response = await draftService.getDrafts(DraftCode.SUBMISSION);

if (req.currentAuthorization?.attributes.includes('scope:self')) {
response = response.filter((x: SubmissionDraft) => x?.createdBy === req.currentContext.userId);
response = response.filter((x: Draft) => x?.createdBy === req.currentContext.userId);
}

res.status(200).json(response);
Expand Down Expand Up @@ -552,23 +553,23 @@ const controller = {
await Promise.all(investigatePermits.map((x: Permit) => permitService.createPermit(x)));

// Delete old draft
if (req.body.submissionDraftId) await submissionDraftService.deleteDraft(req.body.submissionDraftId);
if (req.body.draftId) await draftService.deleteDraft(req.body.draftId);

res.status(201).json({ activityId: result.activityId, submissionId: result.submissionId });
} catch (e: unknown) {
next(e);
}
},

updateDraft: async (req: Request<never, never, SubmissionDraft>, res: Response, next: NextFunction) => {
updateDraft: async (req: Request<never, never, Draft>, res: Response, next: NextFunction) => {
try {
const update = req.body.submissionDraftId && req.body.activityId;
const update = req.body.draftId && req.body.activityId;

let response;

if (update) {
// Update draft
response = await submissionDraftService.updateDraft({
response = await draftService.updateDraft({
...req.body,
...generateUpdateStamps(req.currentContext)
});
Expand All @@ -578,17 +579,16 @@ const controller = {
)?.activityId;

// Create new draft
response = await submissionDraftService.createDraft({
...req.body,
submissionDraftId: uuidv4(),
response = await draftService.createDraft({
draftId: uuidv4(),
activityId: activityId,
draftCode: DraftCode.SUBMISSION,
data: req.body.data,
...generateCreateStamps(req.currentContext)
});
}

res
.status(update ? 200 : 201)
.json({ submissionDraftId: response?.submissionDraftId, activityId: response?.activityId });
res.status(update ? 200 : 201).json({ draftId: response?.draftId, activityId: response?.activityId });
} catch (e: unknown) {
next(e);
}
Expand Down
55 changes: 46 additions & 9 deletions app/src/db/migrations/20241125000000_015-draft-tables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,45 +7,82 @@ export async function up(knex: Knex): Promise<void> {
return Promise.resolve().then(() =>
// Create public schema tables
knex.schema
.createTable('submission_draft', (table) => {
table.uuid('submission_draft_id').primary();
.createTable('draft_code', (table) => {
table.text('draft_code').primary();
stamps(knex, table);
})

.createTable('draft', (table) => {
table.uuid('draft_id').primary();
table
.text('activity_id')
.notNullable()
.references('activity_id')
.inTable('activity')
.onUpdate('CASCADE')
.onDelete('CASCADE');
table
.text('draft_code')
.notNullable()
.references('draft_code')
.inTable('draft_code')
.onUpdate('CASCADE')
.onDelete('CASCADE');
table.json('data').notNullable();
stamps(knex, table);
})

// Create before update triggers
.then(() =>
knex.schema.raw(`CREATE TRIGGER before_update_submission_draft_trigger
BEFORE UPDATE ON submission_draft
knex.schema.raw(`CREATE TRIGGER before_update_draft_code_trigger
BEFORE UPDATE ON draft_code
FOR EACH ROW EXECUTE PROCEDURE public.set_updated_at();`)
)

.then(() =>
knex.schema.raw(`CREATE TRIGGER before_update_draft_trigger
BEFORE UPDATE ON draft
FOR EACH ROW EXECUTE PROCEDURE public.set_updated_at();`)
)

// Create audit triggers
.then(() =>
knex.schema.raw(`CREATE TRIGGER audit_submission_draft_trigger
AFTER UPDATE OR DELETE ON submission_draft
knex.schema.raw(`CREATE TRIGGER audit_draft_code_trigger
AFTER UPDATE OR DELETE ON draft_code
FOR EACH ROW EXECUTE PROCEDURE audit.if_modified_func();`)
)

.then(() =>
knex.schema.raw(`CREATE TRIGGER audit_draft_trigger
AFTER UPDATE OR DELETE ON draft
FOR EACH ROW EXECUTE PROCEDURE audit.if_modified_func();`)
)

// Populate Baseline Data
.then(() => {
const items = [
{
draft_code: 'SUBMISSION'
}
];
return knex('draft_code').insert(items);
})
);
}

export async function down(knex: Knex): Promise<void> {
return (
Promise.resolve()
// Drop audit triggers
.then(() => knex.schema.raw('DROP TRIGGER IF EXISTS audit_submission_draft_trigger ON submission_draft'))
.then(() => knex.schema.raw('DROP TRIGGER IF EXISTS audit_draft_trigger ON draft'))
.then(() => knex.schema.raw('DROP TRIGGER IF EXISTS audit_draft_code_trigger ON draft_code'))

// Drop public schema table triggers
.then(() => knex.schema.raw('DROP TRIGGER IF EXISTS before_update_submission_draft_trigger ON submission_draft'))
.then(() => knex.schema.raw('DROP TRIGGER IF EXISTS before_update_draft_trigger ON draft'))
.then(() => knex.schema.raw('DROP TRIGGER IF EXISTS before_update_draft_code_trigger ON draft_code'))

// Drop public schema tables
.then(() => knex.schema.dropTableIfExists('submission_draft'))
.then(() => knex.schema.dropTableIfExists('draft'))
.then(() => knex.schema.dropTableIfExists('draft_code'))
);
}
22 changes: 22 additions & 0 deletions app/src/db/models/draft.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Prisma } from '@prisma/client';

import type { Draft } from '../../types';

// Define types
const _draft = Prisma.validator<Prisma.draftDefaultArgs>()({});

type PrismaGraphDraft = Prisma.draftGetPayload<typeof _draft>;

export default {
fromPrismaModel(input: PrismaGraphDraft): Draft {
return {
draftId: input.draft_id,
activityId: input.activity_id,
draftCode: input.draft_code,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data: input.data as any,
createdBy: input.created_by,
updatedAt: input.updated_at?.toISOString() ?? null
};
}
};
2 changes: 1 addition & 1 deletion app/src/db/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ export { default as activity } from './activity';
export { default as access_request } from './access_request';
export { default as contact } from './contact';
export { default as document } from './document';
export { default as draft } from './draft';
export { default as enquiry } from './enquiry';
export { default as identity_provider } from './identity_provider';
export { default as note } from './note';
export { default as permit } from './permit';
export { default as permit_note } from './permit_note';
export { default as permit_type } from './permit_type';
export { default as submission } from './submission';
export { default as submission_draft } from './submission_draft';
export { default as user } from './user';
20 changes: 0 additions & 20 deletions app/src/db/models/submission_draft.ts

This file was deleted.

41 changes: 27 additions & 14 deletions app/src/db/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ model activity {
initiative initiative @relation(fields: [initiative_id], references: [initiative_id], onDelete: Cascade, map: "activity_initiative_id_foreign")
activity_contact activity_contact[]
document document[]
draft draft[]
enquiry enquiry[]
note note[]
permit permit[]
submission submission[]
submission_draft submission_draft[]
@@schema("public")
}
Expand Down Expand Up @@ -299,19 +299,6 @@ model submission {
@@schema("public")
}

model submission_draft {
submission_draft_id String @id @db.Uuid
activity_id String
data Json @db.Json
created_by String? @default("00000000-0000-0000-0000-000000000000")
created_at DateTime? @default(now()) @db.Timestamptz(6)
updated_by String?
updated_at DateTime? @db.Timestamptz(6)
activity activity @relation(fields: [activity_id], references: [activity_id], onDelete: Cascade, map: "submission_draft_activity_id_foreign")
@@schema("public")
}

model user {
user_id String @id @db.Uuid
identity_id String? @db.Uuid
Expand Down Expand Up @@ -496,6 +483,32 @@ model subject_group {
@@schema("yars")
}

model draft {
draft_id String @id @db.Uuid
activity_id String
draft_code String
data Json @db.Json
created_by String? @default("00000000-0000-0000-0000-000000000000")
created_at DateTime? @default(now()) @db.Timestamptz(6)
updated_by String?
updated_at DateTime? @db.Timestamptz(6)
activity activity @relation(fields: [activity_id], references: [activity_id], onDelete: Cascade, map: "draft_activity_id_foreign")
draft_code_draft_draft_codeTodraft_code draft_code @relation("draft_draft_codeTodraft_code", fields: [draft_code], references: [draft_code], onDelete: Cascade, map: "draft_draft_code_foreign")
@@schema("public")
}

model draft_code {
draft_code String @id
created_by String? @default("00000000-0000-0000-0000-000000000000")
created_at DateTime? @default(now()) @db.Timestamptz(6)
updated_by String?
updated_at DateTime? @db.Timestamptz(6)
draft_draft_draft_codeTodraft_code draft[] @relation("draft_draft_codeTodraft_code")
@@schema("public")
}

view group_role_policy_vw {
row_number BigInt @unique
group_id Int?
Expand Down
6 changes: 3 additions & 3 deletions app/src/middleware/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { NIL } from 'uuid';

import {
documentService,
draftService,
enquiryService,
noteService,
permitService,
submissionService,
submissionDraftService,
userService,
yarsService
} from '../services';
Expand Down Expand Up @@ -109,11 +109,11 @@ export const hasAuthorization = (resource: string, action: string) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const paramMap = new Map<string, (id: string) => any>([
['documentId', documentService.getDocument],
['draftId', draftService.getDraft],
['enquiryId', enquiryService.getEnquiry],
['noteId', noteService.getNote],
['permitId', permitService.getPermit],
['submissionId', submissionService.getSubmission],
['submissionDraftId', submissionDraftService.getDraft]
['submissionId', submissionService.getSubmission]
]);

/**
Expand Down
Loading

0 comments on commit 980e56a

Please sign in to comment.