-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
343 lines (307 loc) · 10.1 KB
/
app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import { app, errorHandler } from "mu";
import { Request, Response } from "express";
import {
getLastAgendaActivityNumber,
getSortedAgendaitems,
getAgenda,
updatePieceName,
updateAgendaActivityNumber,
} from "./lib/queries";
import CONSTANTS from "./constants";
import { Agenda, Agendaitem, Piece } from "./types/types";
import { getAgendaitemPieces } from "./lib/get-agendaitem-pieces";
import {
createNamingJob,
jobExists,
latestJobFinishedAt,
updateJobStatus,
} from "./lib/jobs";
import { getErrorMessage } from "./lib/utils";
import bodyParser from "body-parser";
import { addPieceOriginalName } from "./lib/add-piece-original-name";
import { getRatification } from './lib/get-ratification';
type FileMapping = {
uri: string;
generatedName: string;
};
app.use(bodyParser.json());
app.get("/agenda/:agenda_id", getNamedPieces);
app.post("/agenda/:agenda_id", async function (req: Request, res: Response) {
const agendaId = req.params["agenda_id"];
if (!agendaId) {
return res.status(404).send(JSON.stringify({
error: `No agenda id supplied`
}));
}
const agenda = await getAgenda(agendaId);
if (!agenda) {
return res
.status(404)
.send(JSON.stringify({
error: `Agenda with id ${agendaId} could not be found.`
}));
}
if (!req.body.clientUpdateTimestamp) {
return res.status(400).send(JSON.stringify({
error: `No clientUpdateTimestamp supplied.`
}));
}
const lastClientUpdateTimestamp = new Date(req.body.clientUpdateTimestamp);
const latestJobTimestamp = await latestJobFinishedAt();
if (latestJobTimestamp && latestJobTimestamp > lastClientUpdateTimestamp) {
return res
.status(409)
.send(JSON.stringify({
error:`Er werd een andere agenda goedgekeurd sinds ${lastClientUpdateTimestamp.toLocaleString('nl-BE')}, ververs de pagina.`,
}));
}
const mappings = req.body.data as FileMapping[];
if (!mappings) {
return res.status(400).send(JSON.stringify({
error: `No piece name mappings supplied`
}));
}
const mappingMap = new Map(
mappings.map(({ uri, generatedName }) => [uri, generatedName])
);
const job = await createNamingJob(
agenda.uri,
mappings.map((doc) => doc.uri)
);
const authorized = await jobExists(job.uri);
if (!authorized) {
return res.status(403).send(JSON.stringify({
error: "You don't have the required access rights to change change document names",
}));
}
const payload = {
data: {
type: CONSTANTS.JOB.JSONAPI_JOB_TYPE,
id: job.id,
attributes: {
uri: job.uri,
status: job.status,
created: job.created,
},
},
};
res.send(payload);
try {
const agendaitems = await getSortedAgendaitems(agendaId);
const counters = await initCounters(agenda);
for (const agendaitem of agendaitems) {
const piecesResults = await getAgendaitemPieces(agendaitem.uri);
const ratification = await getRatification(agendaitem.uri);
if (ratification) {
const allPieces = await getAgendaitemPieces(agendaitem.uri, true);
const maxPosition = Math.max(...allPieces.map((p) => p.position ?? 0));
ratification.position = maxPosition + 1;
piecesResults.push(ratification);
}
ensureAgendaActivityNumber(agendaitem, agenda, counters);
if (agendaitem.agendaActivityNumber === undefined)
throw new Error("No agendaActivityNumber (should never happen)");
for (const piece of piecesResults) {
const newName = mappingMap.get(piece.uri) ?? piece.title;
await updatePieceName(piece.uri, newName);
await addPieceOriginalName(piece.uri, piece.title);
}
await updateAgendaActivityNumber(
agendaitem.uri,
agendaitem.agendaActivityNumber
);
}
const { SUCCESS } = CONSTANTS.JOB.STATUS;
await updateJobStatus(job.uri, SUCCESS);
} catch (e) {
const { FAIL } = CONSTANTS.JOB.STATUS;
await updateJobStatus(job.uri, FAIL, getErrorMessage(e));
}
return;
});
function ensureAgendaActivityNumber(
agendaitem: Agendaitem,
agenda: Agenda,
counters: AgendaActivityCounterDict
): void {
if (agendaitem.agendaActivityNumber === undefined) {
increaseCounters(agenda, agendaitem, counters);
agendaitem.agendaActivityNumber = readCounter(agenda, agendaitem, counters);
}
}
app.use(errorHandler);
type AgendaActivityCounterDict = {
regular: {
doc: number;
med: number;
dec: number;
};
pvv: {
doc: number;
med: number;
dec: number;
};
};
async function initCounters(
agenda: Agenda
): Promise<AgendaActivityCounterDict> {
if (!agenda.meeting.plannedStart) {
throw new Error("Meeting needs a plannedStart");
}
const year = agenda.meeting.plannedStart.getFullYear();
return {
regular: {
doc: await getLastAgendaActivityNumber(year, "nota", false),
med: await getLastAgendaActivityNumber(year, "announcement", false),
dec: await getLastAgendaActivityNumber(year, "decree", false),
},
pvv: {
doc: await getLastAgendaActivityNumber(year, "nota", true),
med: await getLastAgendaActivityNumber(year, "announcement", true),
dec: await getLastAgendaActivityNumber(year, "decree", true),
},
};
}
async function getNamedPieces(req: Request, res: Response) {
const agendaId = req.params["agenda_id"];
if (!agendaId) {
return res.status(404).send(
JSON.stringify({
error: `No agenda id supplied`,
})
);
}
const agenda = await getAgenda(agendaId);
if (!agenda) {
return res.status(404).send(
JSON.stringify({
error: `Agenda with id ${agendaId} could not be found.`,
})
);
}
try {
const agendaitems = await getSortedAgendaitems(agendaId);
const counters = await initCounters(agenda);
const mappings: FileMapping[] = [];
for (const agendaitem of agendaitems) {
const piecesResults = await getAgendaitemPieces(agendaitem.uri);
const ratification = await getRatification(agendaitem.uri);
if (ratification) {
const allPieces = await getAgendaitemPieces(agendaitem.uri, true);
const maxPosition = Math.max(...allPieces.map((p) => p.position ?? 0));
ratification.position = maxPosition + 1;
piecesResults.push(ratification);
}
ensureAgendaActivityNumber(agendaitem, agenda, counters);
for (const piece of piecesResults) {
const generatedName = generateName(agenda, agendaitem, piece);
mappings.push({ uri: piece.uri, generatedName });
}
}
return res.send(mappings);
} catch (error: any) {
return res.status(500).send(
JSON.stringify({
error: `document-naming service ran into an error: ${error?.message}`,
})
);
}
}
function readCounter(
agenda: Agenda,
agendaitem: Agendaitem,
counters: AgendaActivityCounterDict
): number {
const { type: agendaitemType, subcaseType } = agendaitem;
const agendaitemPurpose = getAgendaitemPurpose(agendaitemType, subcaseType);
const isPvv = agenda.meeting.type === CONSTANTS.MEETING_TYPES.PVV;
return counters[isPvv ? "pvv" : "regular"][agendaitemPurpose];
}
function getAgendaitemPurpose(
agendaitemType: string,
subcaseType: string
): "med" | "doc" | "dec" {
if (agendaitemType === CONSTANTS.AGENDA_ITEM_TYPES.MEDEDELING) {
return "med";
} else if (
agendaitemType === CONSTANTS.AGENDA_ITEM_TYPES.NOTA &&
subcaseType === CONSTANTS.SUBCASE_TYPES.BEKRACHTIGING
) {
return "dec";
} else {
return "doc";
}
}
function increaseCounters(
agenda: Agenda,
agendaitem: Agendaitem,
counters: AgendaActivityCounterDict
): void {
const { type: agendaitemType, subcaseType } = agendaitem;
const agendaitemPurpose = getAgendaitemPurpose(agendaitemType, subcaseType);
const isPvv = agenda.meeting.type === CONSTANTS.MEETING_TYPES.PVV;
counters[isPvv ? "pvv" : "regular"][agendaitemPurpose]++;
}
function generateName(
agenda: Agenda,
agendaitem: Agendaitem,
piece: Piece
): string {
const { meeting } = agenda;
const { plannedStart } = meeting;
const { type: agendaitemType, subcaseType } = agendaitem;
const agendaitemPurpose = getAgendaitemPurpose(agendaitemType, subcaseType);
if (!plannedStart) {
console.warn(
`Could not create document name for ${piece.uri}, no planned start for meeting ${meeting.uri}`
);
return piece.title;
}
const isPvv = agenda.meeting.type === CONSTANTS.MEETING_TYPES.PVV;
const padZeros = (x: unknown, n: number) => String(x).padStart(n, "0");
const monthPart = padZeros(plannedStart.getMonth() + 1, 2);
const dayPart = padZeros(plannedStart.getDate(), 2);
const agendaActivityNumber = agendaitem.agendaActivityNumber;
const agendaActivityNumberPart = padZeros(agendaActivityNumber, 4);
const vvPart = isPvv ? "VV " : "";
const agendaitemPurposePart =
agendaitemPurpose === "doc"
? "DOC"
: agendaitemPurpose === "med"
? "MED"
: "DEC";
let documentTypePart = piece.type ? ` - ${piece.type}` : "";
// if the type is not a capitalized abbreviation it should be all lowercase.
const lastChar = documentTypePart?.slice(-1);
if (lastChar && lastChar == lastChar.toLowerCase()) {
documentTypePart = documentTypePart.toLowerCase() || "";
}
const documentVersionPart =
piece.revision > 1
? `${
CONSTANTS.LATIN_ADVERBIAL_NUMERALS[piece.revision - 1]
}`.toUpperCase()
: "";
const removeVersionSuffix = (title: string) => {
const versionSuffixes = `${
`(${Object.values(CONSTANTS.LATIN_ADVERBIAL_NUMERALS)
.map((suffix) => suffix.toUpperCase())
.join(')|(')})`
.replace('()|', '')
}`;
const regex = new RegExp(`(.*?)${versionSuffixes}?$`);
return regex.test(title)
? title
.replace(new RegExp(`${versionSuffixes}$`, 'ui'), '')
.trim()
: title;
};
const title = piece.title.trim();
const subjectPart = removeVersionSuffix(title);
const fullGeneratedName = (
`VR ${plannedStart.getFullYear()} ${dayPart}${monthPart} ${vvPart}` +
`${agendaitemPurposePart}.${agendaActivityNumberPart}-${piece.position} ` +
`${subjectPart}${documentTypePart} ${documentVersionPart}`
);
return fullGeneratedName.trim();
}