Skip to content

Commit 0015a19

Browse files
author
Brijesh
committed
1164 - Ensure status update on versions table and make it match with the table in PDF
1 parent c7c723f commit 0015a19

7 files changed

Lines changed: 146 additions & 163 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
exports.up = async (knex) => {
2+
await knex.raw(`
3+
drop view plan_snapshot_summary
4+
`);
5+
};
6+
7+
exports.down = async () => {};

src/libs/db2/model/model.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ export default class Model {
9191
if (order && order.length > 0) {
9292
results = await q.orderBy(...order);
9393
} else {
94+
// console.log(q.toSQL().toNative());
9495
results = await q;
9596
}
9697

src/libs/db2/model/plansnapshot.js

Lines changed: 94 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import PlanStatus from './planstatus';
55
import { generatePDFResponse } from '../../../router/controllers_v1/PDFGeneration';
66
import Plan from './plan';
77
import PlanStatusHistory from './planstatushistory';
8+
import AmendmentType from './amendmenttype';
89

910
export default class PlanSnapshot extends Model {
1011
constructor(data, db = undefined) {
@@ -71,6 +72,95 @@ export default class PlanSnapshot extends Model {
7172
return objs;
7273
}
7374

75+
static async fetchAmendmentSubmissions(db, planId, startDate) {
76+
const amendmentTypeArray = [];
77+
const amendmentTypeRows = await AmendmentType.find(db, {});
78+
amendmentTypeRows.forEach((element) => {
79+
amendmentTypeArray[element.id] = element.description;
80+
});
81+
const query = db
82+
.select([
83+
'plan_snapshot.id',
84+
'plan_snapshot.plan_id',
85+
'plan_snapshot.version',
86+
'plan_snapshot.snapshot',
87+
'plan_snapshot.status_id',
88+
'plan_snapshot.created_at',
89+
'user_account.family_name',
90+
'user_account.given_name',
91+
])
92+
.table('plan_snapshot')
93+
.leftJoin('user_account', {
94+
'plan_snapshot.user_id': 'user_account.id',
95+
})
96+
.andWhere({
97+
plan_id: planId,
98+
})
99+
.orderBy('plan_snapshot.created_at', 'dsc');
100+
if (startDate) query.andWhere('plan_snapshot.created_at', '<=', startDate);
101+
const response = [];
102+
let lastMandatoryAmendment = null;
103+
const results = await query;
104+
for (let index = 0; index < results.length; index++) {
105+
const row = results[index];
106+
const nextRow = results[index + 1];
107+
row.isCurrentLegalVersion = false;
108+
if (row.status_id === 21) {
109+
response.push({
110+
id: row.id,
111+
version: row.version,
112+
planId: row.plan_id,
113+
createdAt: row.created_at,
114+
submittedBy: `${row.given_name} ${row.family_name}`,
115+
approvedAt: null,
116+
approvedBy: null,
117+
amendmentType: amendmentTypeArray[1],
118+
snapshot: row.snapshot,
119+
});
120+
} else if (row.status_id === 22 || (row.status_id === 23 && nextRow?.status_id !== 21)) {
121+
lastMandatoryAmendment = response.length;
122+
response.push({
123+
id: row.id,
124+
version: row.version,
125+
planId: row.plan_id,
126+
createdAt: row.created_at,
127+
submittedBy: `${row.given_name} ${row.family_name}`,
128+
approvedAt: null,
129+
approvedBy: null,
130+
amendmentType: amendmentTypeArray[2],
131+
snapshot: row.snapshot,
132+
});
133+
} else if (row.status_id === 12 && row.snapshot.amendmentTypeId === null) {
134+
response.push({
135+
id: row.id,
136+
version: row.version,
137+
planId: row.plan_id,
138+
createdAt: null,
139+
submittedBy: null,
140+
approvedAt: row.created_at,
141+
approvedBy: `${row.given_name} ${row.family_name}`,
142+
amendmentType: null,
143+
snapshot: row.snapshot,
144+
});
145+
}
146+
if (Plan.legalStatuses.indexOf(row.status_id) !== -1) {
147+
if (lastMandatoryAmendment !== null) {
148+
response[lastMandatoryAmendment].approvedBy = `${row.given_name} ${row.family_name}`;
149+
response[lastMandatoryAmendment].approvedAt = row.created_at;
150+
response[lastMandatoryAmendment].version = row.version;
151+
response[lastMandatoryAmendment].snapshot = row.snapshot;
152+
lastMandatoryAmendment = null;
153+
}
154+
}
155+
}
156+
const responseReversed = response.reverse();
157+
const currentLegalVersion = responseReversed.find(
158+
(resp) => Plan.legalStatuses.indexOf(resp.snapshot.statusId) !== -1,
159+
);
160+
if (currentLegalVersion) currentLegalVersion.isCurrentLegalVersion = true;
161+
return responseReversed;
162+
}
163+
74164
async fetchStatus(db) {
75165
const status = await PlanStatus.findOne(db, { id: this.statusId });
76166
if (status) {
@@ -90,16 +180,17 @@ export default class PlanSnapshot extends Model {
90180
};
91181
}
92182
values.snapshot.originalApproval = originalApproval;
93-
const amendmentSubmissions = await PlanStatusHistory.fetchAmendmentSubmissions(db, values.plan_id);
94-
values.snapshot.amendmentSubmissions = amendmentSubmissions;
183+
values.snapshot.amendmentSubmissions = await PlanSnapshot.fetchAmendmentSubmissions(db, values.plan_id);
184+
values.snapshot.amendmentSubmissions = values.snapshot.amendmentSubmissions.filter((item) => {
185+
return item.amendmentType !== null;
186+
});
95187
const response = await generatePDFResponse(values.snapshot);
96188
values.pdf_file = response.data;
97189
values.snapshot = JSON.stringify(values.snapshot);
98190
} catch (error) {
99191
throw errorWithCode(`Error creating PDF file: ${JSON.stringify(error)}`, 500);
100192
}
101193
}
102-
console.log(`About to call super`);
103194
await super.create(db, values);
104195
}
105196
}

src/libs/db2/model/planstatushistory.js

Lines changed: 0 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222

2323
'use strict';
2424

25-
import AmendmentType from './amendmenttype';
2625
import Model from './model';
2726
import Plan from './plan';
2827
import User from './user';
@@ -96,67 +95,4 @@ export default class PlanStatusHistory extends Model {
9695
}
9796
return null;
9897
}
99-
100-
static async fetchAmendmentSubmissions(db, planId, startDate) {
101-
const amendmentTypeArray = [];
102-
const amendmentTypeRows = await AmendmentType.find(db, {});
103-
amendmentTypeRows.forEach((element) => {
104-
amendmentTypeArray[element.id] = element.description;
105-
});
106-
const results = await db
107-
.select([
108-
'plan_status_history.id',
109-
'plan_status_history.to_plan_status_id',
110-
'plan_status_history.from_plan_status_id',
111-
'plan_status_history.created_at',
112-
'user_account.family_name',
113-
'user_account.given_name',
114-
])
115-
.table('plan_status_history')
116-
.leftJoin('user_account', {
117-
'plan_status_history.user_id': 'user_account.id',
118-
})
119-
.andWhere({
120-
plan_id: planId,
121-
})
122-
.orderBy('plan_status_history.created_at');
123-
const response = [];
124-
let lastMandatoryAmendment = null;
125-
results.forEach((row) => {
126-
if (
127-
startDate &&
128-
new Date(startDate) < new Date(row.created_at) &&
129-
new Date(startDate).toString() !== new Date(row.created_at).toString()
130-
) {
131-
return;
132-
}
133-
if (row.to_plan_status_id === 21) {
134-
response.push({
135-
id: row.id,
136-
createdAt: row.created_at,
137-
submittedBy: `${row.given_name} ${row.family_name}`,
138-
approvedAt: null,
139-
approvedBy: null,
140-
amendmentType: amendmentTypeArray[1],
141-
});
142-
} else if (row.from_plan_status_id === 22 || row.from_plan_status_id === 23) {
143-
lastMandatoryAmendment = response.length;
144-
response.push({
145-
id: row.id,
146-
createdAt: row.created_at,
147-
submittedBy: `${row.given_name} ${row.family_name}`,
148-
approvedAt: null,
149-
approvedBy: null,
150-
amendmentType: amendmentTypeArray[2],
151-
});
152-
}
153-
if (Plan.legalStatuses.indexOf(row.to_plan_status_id) !== -1) {
154-
if (lastMandatoryAmendment !== null) {
155-
response[lastMandatoryAmendment].approvedBy = `${row.given_name} ${row.family_name}`;
156-
response[lastMandatoryAmendment].approvedAt = row.created_at;
157-
}
158-
}
159-
});
160-
return response.reverse();
161-
}
16298
}

src/router/controllers_v1/PlanController.js

Lines changed: 28 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { checkRequiredFields, objPathToCamelCase, removeCommonFields } from '../
1515
import { PlanRouteHelper } from '../helpers';
1616
import { generatePDFResponse } from './PDFGeneration';
1717
import PlanExtensionRequests from '../../libs/db2/model/planextensionrequests';
18+
import PlanStatusController from './PlanStatusController';
1819

1920
const dm = new DataManager(config);
2021
const { db, Plan, Agreement, PlanConfirmation, PlanStatus, AdditionalRequirement, PlanFile } = dm;
@@ -58,60 +59,30 @@ export default class PlanController {
5859
throw errorWithCode("Plan doesn't exist", 404);
5960
}
6061
const { agreementId } = plan;
61-
const statusId = plan?.status?.id;
62-
63-
const isStaff = user.isAdministrator() || user.isRangeOfficer() || user.isDecisionMaker() || user.canReadAll();
64-
65-
const [privacyVersionRaw] = await PlanSnapshot.findSummary(db, {
66-
plan_id: planId,
67-
privacyview: isStaff ? 'StaffView' : 'AHView',
68-
});
69-
const privacyVersion = privacyVersionRaw?.snapshot;
70-
71-
const shouldBeLiveVersion = privacyVersion == null;
72-
7362
await PlanRouteHelper.canUserAccessThisAgreement(db, Agreement, user, agreementId);
74-
7563
const [agreement] = await Agreement.findWithTypeZoneDistrictExemption(db, { forest_file_id: agreementId });
7664
await agreement.eagerloadAllOneToManyExceptPlan();
7765
agreement.transformToV1();
78-
79-
if (shouldBeLiveVersion) {
80-
await plan.eagerloadAllOneToMany();
81-
plan.agreement = agreement;
82-
83-
const filteredFiles = filterFiles(plan.files, user);
84-
85-
const mappedGrazingSchedules = await Promise.all(
86-
plan.grazingSchedules.map(async (schedule) => {
87-
let sanitizedSortBy = schedule.sortBy && objPathToCamelCase(schedule.sortBy);
88-
sanitizedSortBy = sanitizedSortBy && sanitizedSortBy.replace('pastureName', 'pasture.name');
89-
sanitizedSortBy = sanitizedSortBy && sanitizedSortBy.replace('refLivestockName', 'livestockType.name');
90-
sanitizedSortBy = sanitizedSortBy && sanitizedSortBy.replace('pldAuMs', 'pldAUMs');
91-
sanitizedSortBy = sanitizedSortBy && sanitizedSortBy.replace('crownAuMs', 'crownAUMs');
92-
return {
93-
...schedule,
94-
sortBy: sanitizedSortBy,
95-
};
96-
}),
97-
);
98-
return {
99-
...plan,
100-
grazingSchedules: mappedGrazingSchedules,
101-
files: filteredFiles,
102-
};
103-
}
104-
105-
logger.info('loading last version');
106-
107-
privacyVersion.status_id = statusId;
108-
109-
const filteredFiles = filterFiles(privacyVersion.files, user);
66+
await plan.eagerloadAllOneToMany();
67+
plan.agreement = agreement;
68+
const filteredFiles = filterFiles(plan.files, user);
69+
const mappedGrazingSchedules = await Promise.all(
70+
plan.grazingSchedules.map(async (schedule) => {
71+
let sanitizedSortBy = schedule.sortBy && objPathToCamelCase(schedule.sortBy);
72+
sanitizedSortBy = sanitizedSortBy && sanitizedSortBy.replace('pastureName', 'pasture.name');
73+
sanitizedSortBy = sanitizedSortBy && sanitizedSortBy.replace('refLivestockName', 'livestockType.name');
74+
sanitizedSortBy = sanitizedSortBy && sanitizedSortBy.replace('pldAuMs', 'pldAUMs');
75+
sanitizedSortBy = sanitizedSortBy && sanitizedSortBy.replace('crownAuMs', 'crownAUMs');
76+
return {
77+
...schedule,
78+
sortBy: sanitizedSortBy,
79+
};
80+
}),
81+
);
11082
return {
111-
...privacyVersion,
83+
...plan,
84+
grazingSchedules: mappedGrazingSchedules,
11285
files: filteredFiles,
113-
status: plan.status,
114-
statusId: plan.statusId,
11586
};
11687
} catch (error) {
11788
console.log(error.stack);
@@ -178,7 +149,6 @@ export default class PlanController {
178149

179150
// Don't allow the agreement relation to be updated.
180151
delete body.agreementId;
181-
182152
await Plan.update(db, { id: planId }, body);
183153
const [plan] = await Plan.findWithStatusExtension(db, { 'plan.id': planId }, ['id', 'desc']);
184154
await plan.eagerloadAllOneToMany();
@@ -293,15 +263,7 @@ export default class PlanController {
293263
const agreementId = await Plan.agreementIdForPlanId(db, planId);
294264
await PlanRouteHelper.canUserAccessThisAgreement(db, Agreement, user, agreementId);
295265

296-
const prevLegalVersion = await db
297-
.table('plan_snapshot_summary')
298-
.whereIn('status_id', Plan.legalStatuses)
299-
.andWhere({
300-
plan_id: planId,
301-
})
302-
.orderBy('created_at', 'desc')
303-
.first();
304-
266+
const prevLegalVersion = await PlanStatusController.getLatestLegalVersion(planId);
305267
if (!prevLegalVersion) {
306268
throw errorWithCode('Could not find previous legal version.', 500);
307269
}
@@ -311,7 +273,7 @@ export default class PlanController {
311273
await Plan.restoreVersion(db, planId, prevLegalVersion.version);
312274

313275
const versionsToDiscard = await db
314-
.table('plan_snapshot_summary')
276+
.table('plan_snapshot')
315277
.select('id')
316278
.where({ plan_id: planId })
317279
.andWhereRaw('created_at > ?::timestamp', [prevLegalVersion.created_at.toISOString()]);
@@ -329,7 +291,7 @@ export default class PlanController {
329291
const { params, user, body } = req;
330292
const { planId } = params;
331293

332-
if (!user || !user.isRangeOfficer()) {
294+
if (!user || (!user.isRangeOfficer() && !user.isAdministrator())) {
333295
throw errorWithCode('Unauthorized', 403);
334296
}
335297

@@ -352,8 +314,7 @@ export default class PlanController {
352314
static async updateAttachment(req, res) {
353315
const { params, user, body } = req;
354316
const { planId, attachmentId } = params;
355-
356-
if (!user || !user.isRangeOfficer()) {
317+
if (!user || (!user.isRangeOfficer() && !user.isAdministrator())) {
357318
throw errorWithCode('Unauthorized', 403);
358319
}
359320

@@ -380,7 +341,7 @@ export default class PlanController {
380341
const { params, user } = req;
381342
const { planId, attachmentId } = params;
382343

383-
if (!user || !user.isRangeOfficer()) {
344+
if (!user || (!user.isRangeOfficer() && !user.isAdministrator())) {
384345
throw errorWithCode('Unauthorized', 403);
385346
}
386347

@@ -586,8 +547,10 @@ export default class PlanController {
586547
const { planId } = params;
587548
const plan = await PlanController.fetchPlan(planId, user);
588549
plan.originalApproval = await PlanStatusHistory.fetchOriginalApproval(db, planId);
589-
const amendmentSubmissions = await PlanStatusHistory.fetchAmendmentSubmissions(db, planId);
590-
plan.amendmentSubmissions = amendmentSubmissions;
550+
const amendmentSubmissions = await PlanSnapshot.fetchAmendmentSubmissions(db, planId);
551+
plan.amendmentSubmissions = amendmentSubmissions.filter((item) => {
552+
return item.amendmentType !== null;
553+
});
591554
const response = await generatePDFResponse(plan);
592555
res.json(response.data).end();
593556
}

0 commit comments

Comments
 (0)