CJVT updates August and September 2026

This commit is contained in:
Luka Romih
2026-10-01 00:49:26 +02:00
parent fd02e25719
commit 83f73aeb58
135 changed files with 6146 additions and 1970 deletions
+228 -134
View File
@@ -1,13 +1,19 @@
const { mkdir, open, unlink } = require('fs/promises')
const Cursor = require('pg-cursor')
const db = require('./db')
const { intoDbArray, getInstanceSetting } = require('./helpers')
const {
intoDbArray,
getInstanceSetting,
escapeLikePattern
} = require('./helpers')
const {
deserialize,
bulkIndex,
getExportFilesPath
getExportFilesPath,
insertSuggestionEntry
} = require('./helpers/dictionary')
const { readFileIntoDb } = require('./helpers/dictionary/import-file')
const { readJsonFileIntoDb } = require('./helpers/dictionary/import-json-file')
const { transformAndAppend } = require('./helpers/dictionary/export-file')
const { origin } = require('../config/keys')
// const debug = require('debug')('termPortal:models/dictionary')
@@ -35,8 +41,8 @@ class Dictionary {
this.countComments = countComments
}
// Fetch all dictionaries from DB.
static async fetchAll(determinedLanguage) {
// Fetch all published dictionaries from DB.
static async fetchAllPublished(determinedLanguage) {
// TODO Implement SQL stored procedures or functions.
const { rows: fetchedDictionaries } = await db.query(`
SELECT
@@ -47,6 +53,7 @@ class Dictionary {
count_entries,
count_comments
FROM dictionary
WHERE status = 'published'
ORDER BY time_modified DESC`)
const deserializedDictionaries = fetchedDictionaries.map(
dictionary => new this(dictionary)
@@ -129,6 +136,16 @@ class Dictionary {
return deserializedDomains
}
// Fetch all secondary domains from DB, approved or not (for admin filtering).
static async fetchAllSecondaryDomainsUnfiltered(determinedLanguage) {
const { rows: fetchedDomains } = await db.query(`
SELECT id, name_${determinedLanguage} name
FROM domain_secondary
ORDER BY name_${determinedLanguage}`)
return fetchedDomains
}
// Fetch all languages from DB.
static async fetchAllLanguages(determinedLanguage, excludeSlovene) {
// TODO Implement SQL stored procedures or functions.
@@ -223,6 +240,37 @@ class Dictionary {
return deserializedSecondaryDomains
}
// Soft-warning check: does any of the given (non-null) names collide with another own dictionary?
static async checkNameCollision({
nameSl,
nameSlShort,
nameEn,
excludeDictionaryId
}) {
const values = [
nameSl || null,
nameSlShort || null,
nameEn || null,
excludeDictionaryId || null
]
const text = `
SELECT id
FROM dictionary
WHERE
count_comments IS NOT NULL AND
($4::int IS NULL OR id <> $4) AND
(
($1::varchar IS NOT NULL AND name_sl = $1) OR
($2::varchar IS NOT NULL AND name_sl_short = $2) OR
($3::varchar IS NOT NULL AND name_en = $3)
)
LIMIT 1`
const { rows } = await db.query(text, values)
return rows.length > 0
}
// Update single dictionary description in DB.
static async updateDescription(dictionaryId, dictionary) {
const values = [
@@ -254,7 +302,7 @@ class Dictionary {
}
// Delete secondary domain associations with a single dictionary from DB.
static async deleteSecondaryDomains(dictionaryId, dictionary) {
static async deleteSecondaryDomains(dictionaryId, dictionary, dbClient = db) {
const value = [dictionaryId]
const text = `
@@ -262,11 +310,11 @@ class Dictionary {
dictionary_domain_secondary
WHERE
dictionary_id = $1`
await db.query(text, value)
await dbClient.query(text, value)
}
// Insert new secondary domain associations with a single dictionary into DB.
static async updateSecondaryDomains(dictionaryId, dictionary) {
static async updateSecondaryDomains(dictionaryId, dictionary, dbClient = db) {
const updatedSecondaryDomains = intoDbArray(
dictionary.domainSecondary,
'always'
@@ -276,7 +324,15 @@ class Dictionary {
const text = `
INSERT INTO dictionary_domain_secondary (dictionary_id, domain_secondary_id)
VALUES ($1, UNNEST($2::smallint[]))`
await db.query(text, values)
await dbClient.query(text, values)
}
// Replace a dictionary's secondary domain associations atomically.
static async updateSecondaryDomainAssociations(dictionaryId, dictionary) {
await db.transaction(async dbClient => {
await this.deleteSecondaryDomains(dictionaryId, dictionary, dbClient)
await this.updateSecondaryDomains(dictionaryId, dictionary, dbClient)
})
}
// Fetch single dictionary data for editing users from DB.
@@ -395,7 +451,7 @@ class Dictionary {
d.id,
d.name_${determinedLanguage} dictionarysl,
d.count_entries,
to_char(d.time_modified,'YYYY-MM-DD') time_modified,
d.time_modified,
d.issn,
d.author,
dp.name_${determinedLanguage} domain_primary,
@@ -431,7 +487,7 @@ class Dictionary {
distinct(d.id),
${lang} dictionarysl,
d.count_entries,
to_char(d.time_modified,'YYYY-MM-DD') time_modified,
d.time_modified,
d.issn,
d.author,
dp.name_sl domain_primary,
@@ -452,73 +508,6 @@ class Dictionary {
return rows
}
// Fetch dictionary data for viewing details about it
static async fetchBasicInfoPerPageFiltered(
searchQuery,
domainQuery,
resultsPerPage,
page
) {
let queryAppend = ''
if (domainQuery.length > 0) {
try {
queryAppend = domainQuery.reduce((acc, e, i) => {
if (i === 0) {
let retstring = `( dp.id=${parseInt(e)}`
if (domainQuery.length - 1 === 0) {
// if contains only one item -> "AND (dp.id=XXX)"
retstring = `${retstring} )`
}
// "AND [[( dp.id=XXX]]"
return acc + retstring
}
if (i === domainQuery.length - 1) {
return acc + ` OR dp.id=${parseInt(e)})`
}
// "AND ( dp.id=XXX [[OR dp.id=YYY]]"
return acc + ` OR dp.id=${parseInt(e)}`
}, 'AND ')
} catch (e) {
queryAppend = ''
}
}
const isInEnglish = false
const lang = isInEnglish ? 'name_en' : 'name_sl'
const text = `
SELECT
distinct (d.id),
d.${lang} dictionarysl,
d.count_entries,
to_char(d.time_modified,'YYYY-MM-DD') time_modified,
d.issn,
d.author,
dp.name_sl domain_primary,
description,
lp.name portalnamesl,
lp.code portalcode
FROM
dictionary d
FULL JOIN dictionary_language dl ON dl.dictionary_id = d.id
INNER JOIN domain_primary dp ON d.domain_primary_id = dp.id
LEFT JOIN linked_dictionary ld ON ld.target_dictionary_id = d.id
LEFT JOIN linked_portal lp ON ld.linked_portal_id = lp.id
WHERE d.name_sl LIKE '%' || $1 || '%' ${queryAppend}
LIMIT $2
OFFSET $3`
const { rows } = await db.query(text, [
searchQuery,
resultsPerPage,
resultsPerPage * (page - 1)
])
return rows
}
// Fetch dictionary data for viewing details about it
static async fetchBasicInfoPerPageFilteredWithOrdering(
searchQuery,
@@ -529,6 +518,10 @@ class Dictionary {
orderIndex,
determinedLanguage
) {
// Escaped so literal %/_ in a search term are matched as themselves,
// not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js.
const escapedSearchQuery = escapeLikePattern(searchQuery)
let queryAppend = ''
if (domainQuery.length > 0) {
try {
@@ -567,7 +560,7 @@ class Dictionary {
d.name_${determinedLanguage} dictionarysl,
d.count_entries,
d.count_comments,
to_char(d.time_modified,'YYYY-MM-DD') time_modified,
d.time_modified,
d.issn,
d.author,
dp.name_${determinedLanguage} domain_primary,
@@ -586,7 +579,7 @@ class Dictionary {
OFFSET $3`
const { rows } = await db.query(text, [
searchQuery,
escapedSearchQuery,
resultsPerPage,
resultsPerPage * (page - 1)
])
@@ -596,6 +589,10 @@ class Dictionary {
// Fetch dictionary data for viewing details about it
static async fetchFilteredCount(searchQuery, domainQuery) {
// Escaped so literal %/_ in a search term are matched as themselves,
// not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js.
const escapedSearchQuery = escapeLikePattern(searchQuery)
let queryAppend = ''
if (domainQuery.length > 0) {
try {
@@ -635,7 +632,7 @@ class Dictionary {
LEFT JOIN linked_portal lp ON ld.linked_portal_id = lp.id
WHERE d.status = 'published' AND d.name_sl LIKE '%' || $1 || '%' ${queryAppend}`
const { rows } = await db.query(text, [searchQuery])
const { rows } = await db.query(text, [escapedSearchQuery])
return rows[0]
}
@@ -789,7 +786,7 @@ class Dictionary {
}
// Delete language associations with a single dictionary from DB.
static async deleteLanguages(dictionaryId) {
static async deleteLanguages(dictionaryId, dbClient = db) {
const value = [dictionaryId]
const text = `
@@ -797,11 +794,11 @@ class Dictionary {
dictionary_language
WHERE
dictionary_id = $1`
await db.query(text, value)
await dbClient.query(text, value)
}
// Insert new language associations with a single dictionary into DB.
static async updateLanguages(dictionaryId, dictionary) {
static async updateLanguages(dictionaryId, dictionary, dbClient = db) {
const updatedLanguages = intoDbArray(dictionary.language, 'always')
const selectionOrder = updatedLanguages.map((language, index) => index + 1)
const values = [dictionaryId, updatedLanguages, selectionOrder]
@@ -809,15 +806,69 @@ class Dictionary {
const text = `
INSERT INTO dictionary_language (dictionary_id, language_id, selection_order)
VALUES ($1, UNNEST($2::smallint[]), UNNEST($3::smallint[]))`
await db.query(text, values)
await dbClient.query(text, values)
}
// Replace a dictionary's language associations atomically.
static async updateLanguageAssociations(dictionaryId, dictionary) {
await db.transaction(async dbClient => {
await this.deleteLanguages(dictionaryId, dbClient)
await this.updateLanguages(dictionaryId, dictionary, dbClient)
})
}
static async fetchAllAdminDictionaries(
determinedLanguage,
resultsPerPage,
page
page,
sortBy,
sortDir,
filters = {}
) {
// TODO Implement SQL stored procedures or functions.
// sortBy/sortDir must already be whitelisted by the caller (see
// controllers/helpers/dictionary.js resolveDictionarySort) - this map is
// a defense-in-depth fallback, never interpolate req.query values directly.
const sortColumns = {
id: 'id',
name: `name_${determinedLanguage}`,
status: 'status',
timeCreated: 'time_created',
timeModified: 'time_modified'
}
const sortColumn = sortColumns[sortBy] || 'id'
const direction = sortDir === 'asc' ? 'ASC' : 'DESC'
// A category left unselected must be passed as null (not []) so the
// "$n::type[] IS NULL" branch short-circuits it as "no filter" - an
// empty array would instead match zero rows via "= ANY('{}')".
const {
nameQuery = '',
primaryDomainIds = null,
secondaryDomainIds = null,
languageIds = null,
statuses = null
} = filters
// Escaped so literal %/_ in a search term (e.g. a dictionary named
// "100%") are matched as themselves, not as LIKE wildcards - see
// escapeLikePattern in models/helpers/index.js for wildcard-search notes.
const escapedNameQuery = escapeLikePattern(nameQuery)
const whereClause = `
WHERE count_comments IS NOT NULL
AND ($3 = '' OR LOWER(name_${determinedLanguage}) LIKE '%' || LOWER($3) || '%')
AND ($4::smallint[] IS NULL OR domain_primary_id = ANY($4::smallint[]))
AND ($5::dictionary_status[] IS NULL OR status = ANY($5::dictionary_status[]))
AND ($6::smallint[] IS NULL OR EXISTS (
SELECT 1 FROM dictionary_domain_secondary dds
WHERE dds.dictionary_id = dictionary.id AND dds.domain_secondary_id = ANY($6::smallint[])
))
AND ($7::smallint[] IS NULL OR EXISTS (
SELECT 1 FROM dictionary_language dl
WHERE dl.dictionary_id = dictionary.id AND dl.language_id = ANY($7::smallint[])
))`
const {
rows: [{ result }]
} = await db.query(
@@ -826,6 +877,7 @@ class Dictionary {
'pages_total', (
SELECT CEIL(COUNT(*) / $1::float)
FROM dictionary
${whereClause}
),
'results', ARRAY(
SELECT jsonb_build_object(
@@ -836,12 +888,21 @@ class Dictionary {
'status', status
)
FROM dictionary
WHERE count_comments IS NOT NULL
${whereClause}
ORDER BY ${sortColumn} ${direction}, id ${direction}
LIMIT $1
OFFSET $2
)
) result`,
[resultsPerPage, resultsPerPage * (page - 1)]
[
resultsPerPage,
resultsPerPage * (page - 1),
escapedNameQuery,
primaryDomainIds,
statuses,
secondaryDomainIds,
languageIds
]
)
return result
@@ -959,7 +1020,31 @@ class Dictionary {
delete_existing_entries,
file_format
)
VALUES ($1, $2, $3)`
VALUES ($1, $2, $3)
RETURNING id`
const {
rows: [{ id }]
} = await db.query(text, values)
return id
}
// Update import file job in DB with its final status and entry counts.
static async closeImportFileJob(
jobId,
status,
countValidEntries,
countInvalidEntries
) {
const values = [jobId, status, countValidEntries, countInvalidEntries]
const text = `
UPDATE import_file_job
SET
status = $2,
count_valid_entries = $3,
count_invalid_entries = $4
WHERE id = $1`
await db.query(text, values)
}
@@ -969,20 +1054,30 @@ class Dictionary {
userId,
dictionaryId,
importFilePath,
entryStatus
entryStatus,
importFileFormat
) {
const dbClient = await db.getClient()
try {
await dbClient.query('BEGIN')
await readFileIntoDb(
userId,
dictionaryId,
importFilePath,
entryStatus,
dbClient
)
const { totalCount, validCount } =
importFileFormat === 'json_term_candidates'
? await readJsonFileIntoDb(
userId,
dictionaryId,
importFilePath,
dbClient
)
: await readFileIntoDb(
userId,
dictionaryId,
importFilePath,
entryStatus,
dbClient
)
await this.updateMetadataAfterModifyingEntries(dictionaryId, dbClient)
await dbClient.query('COMMIT')
return { totalCount, validCount }
} catch (error) {
await dbClient.query('ROLLBACK')
throw error
@@ -999,31 +1094,7 @@ class Dictionary {
kanonicnaoblika: term,
definicija: other
} of termCandidates) {
const values = [
dictionaryId,
false,
'suggestion',
term || null,
userId,
null,
null,
null,
null,
[],
null,
null,
null,
[],
other || null,
[],
null,
null,
null
]
const text = `SELECT entry_new (${db.genParamStr(values)})`
await dbClient.query(text, values)
await insertSuggestionEntry(dbClient, dictionaryId, userId, term, other)
}
await this.updateMetadataAfterModifyingEntries(dictionaryId, dbClient)
@@ -1214,6 +1285,10 @@ class Dictionary {
resultsPerPage,
page
) {
// Escaped so literal %/_ in a search term are matched as themselves,
// not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js.
const escapedQuery = escapeLikePattern(query)
const {
rows: [{ result }]
} = await db.query(
@@ -1237,7 +1312,7 @@ class Dictionary {
OFFSET $4
)
) result`,
[dictionaryId, query, resultsPerPage, resultsPerPage * (page - 1)]
[dictionaryId, escapedQuery, resultsPerPage, resultsPerPage * (page - 1)]
)
return result
@@ -1275,6 +1350,10 @@ class Dictionary {
// Fetch filtered secondary domains from DB.
static async fetchFilteredSecondaryDomains(query, resultsPerPage, page) {
// Escaped so literal %/_ in a search term are matched as themselves,
// not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js.
const escapedQuery = escapeLikePattern(query)
const {
rows: [{ result }]
} = await db.query(
@@ -1299,7 +1378,7 @@ class Dictionary {
OFFSET $3
)
) result`,
[query, resultsPerPage, resultsPerPage * (page - 1)]
[escapedQuery, resultsPerPage, resultsPerPage * (page - 1)]
)
return result
@@ -1501,10 +1580,11 @@ class Dictionary {
'status', status,
'delete_existing_entries', delete_existing_entries,
'file_format', file_format,
'count_valid_entries', count_valid_entries
'count_entries', count_valid_entries + count_invalid_entries
)
FROM import_file_job
WHERE dictionary_id = $1
ORDER BY id DESC
LIMIT $2
OFFSET $3
)
@@ -1572,6 +1652,7 @@ class Dictionary {
)
FROM dictionary_export
WHERE dictionary_id = $1
ORDER BY id DESC
LIMIT $2
OFFSET $3
)
@@ -1590,9 +1671,10 @@ class Dictionary {
is_terminology_reviewed_filter,
is_language_reviewed_filter,
status_filter,
export_file_format
export_file_format,
time_zone
)
VALUES ($1, $2, $3, $4, $5, $6, $7)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id
`
@@ -1603,7 +1685,8 @@ class Dictionary {
exportParams.isTerminologyReviewedFilter,
exportParams.isLanguageReviewedFilter,
exportParams.statusFilter,
exportParams.exportFileFormat
exportParams.exportFileFormat,
exportParams.timeZone
]
const {
@@ -1613,6 +1696,13 @@ class Dictionary {
return id
}
static async deleteExport(dictionaryId, exportId) {
await db.query(
'DELETE FROM dictionary_export WHERE id = $1 AND dictionary_id = $2',
[exportId, dictionaryId]
)
}
static async processExport(exportId) {
const dbClient = await db.getClient()
let exportFilePath
@@ -1631,7 +1721,8 @@ class Dictionary {
is_terminology_reviewed_filter,
is_language_reviewed_filter,
status_filter,
export_file_format
export_file_format,
COALESCE(time_zone, 'UTC') time_zone
`
const exportQueryParams = [exportId]
@@ -1645,7 +1736,8 @@ class Dictionary {
is_terminology_reviewed_filter: isTerminologyReviewedFilter,
is_language_reviewed_filter: isLanguageReviewedFilter,
status_filter: statusFilter,
export_file_format: exportFileFormat
export_file_format: exportFileFormat,
time_zone: timeZone
}
]
} = await dbClient.query(exportQueryText, exportQueryParams)
@@ -1865,17 +1957,17 @@ class Dictionary {
name_sl,
name_en,
author,
to_char(time_modified, 'YYYY-MM-DD') modified_date_string,
to_char(time_modified AT TIME ZONE $3, 'YYYY-MM-DD') modified_date_string,
status,
(
SELECT to_char(time_created, 'YYYY-MM-DD')
SELECT to_char(time_created AT TIME ZONE $3, 'YYYY-MM-DD')
FROM dictionary_export de
WHERE de.id = $1
) export_date_string
FROM dictionary
WHERE id = $2
`,
[exportId, dictionaryId]
[exportId, dictionaryId, timeZone]
)
const portalName = await getInstanceSetting('portal_name_sl')
const authorsString = tbxMetadata.author?.join(', ')
@@ -1947,7 +2039,9 @@ class Dictionary {
"UPDATE dictionary_export SET status = 'failed', time_finished = NOW() WHERE id = $1",
[exportId]
)
await unlink(exportFilePath)
if (exportFilePath) {
await unlink(exportFilePath).catch(() => {})
}
throw error
} finally {
dbClient.release()
@@ -1964,7 +2058,7 @@ class Dictionary {
e.status,
e.dictionary_id,
d.name_sl_short name_string,
to_char(e.time_created, 'YYYYMMDDHH24MISS') time_string,
to_char(e.time_created AT TIME ZONE COALESCE(e.time_zone, 'UTC'), 'YYYYMMDDHH24MISS') time_string,
e.export_file_format
FROM dictionary_export e
LEFT JOIN dictionary d ON d.id = e.dictionary_id