@parsable/plugin-author-cli 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +405 -0
- package/bin/run +5 -0
- package/bin/run.cmd +3 -0
- package/oclif.manifest.json +1 -0
- package/package.json +67 -0
- package/src/commands/base.js +38 -0
- package/src/commands/exec-data/delete.js +161 -0
- package/src/commands/jobs/create.js +100 -0
- package/src/commands/jobs/delete.js +97 -0
- package/src/commands/template/copy/status.js +66 -0
- package/src/commands/template/copy.js +191 -0
- package/src/config/index.js +40 -0
- package/src/index.js +1 -0
- package/src/services/client/admin.js +81 -0
- package/src/services/client/copy-template-status-client-fn.js +18 -0
- package/src/services/client/create-template-client-fn.js +19 -0
- package/src/services/client/field-data.js +29 -0
- package/src/services/client/helpers/create-user-agent-header.js +13 -0
- package/src/services/client/helpers/create-wi-platform-header.js +3 -0
- package/src/services/client/index.js +11 -0
- package/src/services/client/mothership-client-fn.js +15 -0
- package/src/services/exec-data/delete-fn.js +41 -0
- package/src/services/exec-data/index.js +9 -0
- package/src/services/helpers/convert-kebab-case-to-camel-case.js +6 -0
- package/src/services/helpers/custom-exception.js +12 -0
- package/src/services/helpers/delay-resolve.js +8 -0
- package/src/services/helpers/serial-async-csv-reader.js +53 -0
- package/src/services/jobs/create-fn.js +106 -0
- package/src/services/jobs/delete-fn.js +175 -0
- package/src/services/jobs/index.js +11 -0
- package/src/services/render/helper/std-err-log.js +4 -0
- package/src/services/render/helper/translations.js +107 -0
- package/src/services/render/index.js +15 -0
- package/src/services/render/render-copy-template-success-fn.js +22 -0
- package/src/services/render/render-exception-fn.js +37 -0
- package/src/services/render/render-statuses-fn.js +51 -0
- package/src/services/template_copy/create-lambda-payload.js +36 -0
- package/src/services/template_copy/get-auth-token-fn.js +33 -0
- package/src/services/template_copy/get-config-from-path.js +13 -0
- package/src/services/template_copy/getConfigFromFlagsAndPrompts/convert-inputs-to-config-format.js +9 -0
- package/src/services/template_copy/getConfigFromFlagsAndPrompts/create-questions-for-prompt.js +129 -0
- package/src/services/template_copy/getConfigFromFlagsAndPrompts/find-missing-required-flags.js +30 -0
- package/src/services/template_copy/getConfigFromFlagsAndPrompts/index.js +24 -0
- package/src/services/template_copy/helpers/config-json.schema.js +79 -0
- package/src/services/template_copy/helpers/config-to-payload.map.js +37 -0
- package/src/services/template_copy/helpers/prompt-to-config.map.js +64 -0
- package/src/services/template_copy/index.js +21 -0
- package/src/services/template_copy/send-copy-template-request-fn.js +21 -0
- package/src/services/template_copy/validate-config-json-fn.js +19 -0
- package/src/services/template_status/get-status-fn.js +30 -0
- package/src/services/template_status/index.js +11 -0
- package/src/services/template_status/prompt.js +34 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
const _get = require('lodash/get')
|
|
2
|
+
const debug = require('debug')('app:services:client:admin')
|
|
3
|
+
|
|
4
|
+
const ADMIN_BASE_PATH = '/api/admin'
|
|
5
|
+
|
|
6
|
+
const AdminApiClient = function ({client}) {
|
|
7
|
+
if (!client) {
|
|
8
|
+
throw new Error('client is required for Admin Api Client')
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
this.deleteJobById = async (teamId, id) => {
|
|
12
|
+
debug(`deleting team ${teamId} job ${id}`)
|
|
13
|
+
const path = `${ADMIN_BASE_PATH}/teams/${teamId}/jobs/${id}`
|
|
14
|
+
|
|
15
|
+
return awaitResponse(client.delete(path))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
this.getJobByLookupId = async (teamId, lookupId) => {
|
|
19
|
+
debug(`getting team ${teamId} job ${lookupId}`)
|
|
20
|
+
const path = `${ADMIN_BASE_PATH}/teams/${teamId}/jobs?lookupId=${lookupId}`
|
|
21
|
+
|
|
22
|
+
return awaitResponse(client.get(path))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const awaitResponse = async responsePromise => {
|
|
26
|
+
try {
|
|
27
|
+
return responseObject(await responsePromise)
|
|
28
|
+
} catch (error) {
|
|
29
|
+
const response = _get(error, ['response'])
|
|
30
|
+
if (response) {
|
|
31
|
+
return responseObject(response)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
throw error
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const responseObject = requestErr => {
|
|
39
|
+
const responseText = _get(requestErr, ['text'], '{}')
|
|
40
|
+
let responseBody
|
|
41
|
+
try {
|
|
42
|
+
responseBody = JSON.parse(responseText)
|
|
43
|
+
} catch (error) {
|
|
44
|
+
responseBody = {message: responseText}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return {status: requestErr.status, body: transformErrorResponse(responseBody)}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const transformErrorResponse = body => {
|
|
51
|
+
let response = {
|
|
52
|
+
job: body.job,
|
|
53
|
+
message: body.message,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (body.details) {
|
|
57
|
+
const level1Jobs = _get(body, ['details', 'descendants', 'level1', 'jobIds'], [])
|
|
58
|
+
const level1Issues = _get(body, ['details', 'descendants', 'level1', 'issueIds'], [])
|
|
59
|
+
|
|
60
|
+
const level2Jobs = _get(body, ['details', 'descendants', 'level2', 'jobIds'], [])
|
|
61
|
+
const level2Issues = _get(body, ['details', 'descendants', 'level2', 'issueIds'], [])
|
|
62
|
+
|
|
63
|
+
response.details = {
|
|
64
|
+
descendants: {
|
|
65
|
+
level1: {
|
|
66
|
+
jobs: level1Jobs,
|
|
67
|
+
issues: level1Issues,
|
|
68
|
+
},
|
|
69
|
+
level2: {
|
|
70
|
+
jobs: level2Jobs,
|
|
71
|
+
issues: level2Issues,
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return response
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = AdminApiClient
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const got = require('got')
|
|
2
|
+
|
|
3
|
+
const createUserAgentHeader = require('./helpers/create-user-agent-header.js')
|
|
4
|
+
const createWiPlatformHeader = require('./helpers/create-wi-platform-header.js')
|
|
5
|
+
|
|
6
|
+
module.exports = function ({config, appVersion}) {
|
|
7
|
+
const urlPrefix = config.copyTemplateStatus.urlPrefix
|
|
8
|
+
|
|
9
|
+
return got.extend({
|
|
10
|
+
headers: {
|
|
11
|
+
'User-Agent': createUserAgentHeader(),
|
|
12
|
+
'Wi-Platform': createWiPlatformHeader(),
|
|
13
|
+
'Wi-App-Version': appVersion || 'unknown',
|
|
14
|
+
},
|
|
15
|
+
responseType: 'json',
|
|
16
|
+
prefixUrl: urlPrefix,
|
|
17
|
+
})
|
|
18
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const got = require('got')
|
|
2
|
+
|
|
3
|
+
const createUserAgentHeader = require('./helpers/create-user-agent-header.js')
|
|
4
|
+
const createWiPlatformHeader = require('./helpers/create-wi-platform-header.js')
|
|
5
|
+
|
|
6
|
+
module.exports = function ({config, appVersion}) {
|
|
7
|
+
const url = config.copyTemplateService.url
|
|
8
|
+
|
|
9
|
+
return got.extend({
|
|
10
|
+
headers: {
|
|
11
|
+
'User-Agent': createUserAgentHeader(),
|
|
12
|
+
'Wi-Platform': createWiPlatformHeader(),
|
|
13
|
+
'Wi-App-Version': appVersion || 'unknown',
|
|
14
|
+
},
|
|
15
|
+
responseType: 'json',
|
|
16
|
+
timeout: 240000,
|
|
17
|
+
url,
|
|
18
|
+
})
|
|
19
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const {ApiUtils} = require('@wearableintelligence/parsable-cli-common')
|
|
2
|
+
const {parseThriftJsonResponse} = ApiUtils
|
|
3
|
+
const CustomException = require('../helpers/custom-exception.js')
|
|
4
|
+
|
|
5
|
+
const FIELD_DATA_PATH = '/api/field_data'
|
|
6
|
+
|
|
7
|
+
const FieldDataApiClient = function ({client}) {
|
|
8
|
+
if (!client) {
|
|
9
|
+
throw new Error('client is required for Field Data Api Client')
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
this.deleteFieldData = async ({fieldLocator, opts}) => {
|
|
13
|
+
const payload = {
|
|
14
|
+
method: 'deleteFieldData',
|
|
15
|
+
arguments: {
|
|
16
|
+
fieldLocator,
|
|
17
|
+
opts,
|
|
18
|
+
},
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const [result, err] = parseThriftJsonResponse(await client.post(FIELD_DATA_PATH, payload))
|
|
22
|
+
if (err) {
|
|
23
|
+
throw new CustomException({name: 'EXEC_DATA_DELETE_REQUEST_FAILED', cause: new Error(err.message), info: {fieldId: fieldLocator.fieldId, jobBaseStepId: fieldLocator.jobBaseStepId}})
|
|
24
|
+
}
|
|
25
|
+
return result
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
module.exports = FieldDataApiClient
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const pkg = require('../../../../package.json')
|
|
2
|
+
const _get = require('lodash/get')
|
|
3
|
+
const os = require('os')
|
|
4
|
+
|
|
5
|
+
module.exports = function () {
|
|
6
|
+
const name = _get(pkg, ['name'])
|
|
7
|
+
const version = _get(pkg, ['version'])
|
|
8
|
+
const osType = os.type()
|
|
9
|
+
const arch = os.arch()
|
|
10
|
+
const nodeVersion = process.version
|
|
11
|
+
|
|
12
|
+
return `${name}/${version} (${osType} ${arch}) node/${nodeVersion}`
|
|
13
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const mothershipClientFn = require('./mothership-client-fn.js')
|
|
2
|
+
const copyTemplateClientFn = require('./create-template-client-fn.js')
|
|
3
|
+
const copyTemplateStatusClientFn = require('./copy-template-status-client-fn.js')
|
|
4
|
+
|
|
5
|
+
module.exports = function (deps) {
|
|
6
|
+
return {
|
|
7
|
+
mothershipClient: mothershipClientFn(deps),
|
|
8
|
+
copyTemplateClient: copyTemplateClientFn(deps),
|
|
9
|
+
copyTemplateStatusClient: copyTemplateStatusClientFn(deps),
|
|
10
|
+
}
|
|
11
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const got = require('got')
|
|
2
|
+
|
|
3
|
+
const createUserAgentHeader = require('./helpers/create-user-agent-header.js')
|
|
4
|
+
const createWiPlatformHeader = require('./helpers/create-wi-platform-header.js')
|
|
5
|
+
|
|
6
|
+
module.exports = function ({appVersion}) {
|
|
7
|
+
return got.extend({
|
|
8
|
+
headers: {
|
|
9
|
+
'User-Agent': createUserAgentHeader(),
|
|
10
|
+
'Wi-Platform': createWiPlatformHeader(),
|
|
11
|
+
'Wi-App-Version': appVersion || 'unknown',
|
|
12
|
+
},
|
|
13
|
+
responseType: 'json',
|
|
14
|
+
})
|
|
15
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const {cli} = require('cli-ux')
|
|
2
|
+
|
|
3
|
+
const serialAsyncCsvReader = require('../helpers/serial-async-csv-reader')
|
|
4
|
+
const delayResolve = require('../helpers/delay-resolve')
|
|
5
|
+
|
|
6
|
+
const DELAY = 2000
|
|
7
|
+
|
|
8
|
+
module.exports = function ({fieldDataClient, render}) {
|
|
9
|
+
return async function ({fieldId, jobBaseStepId, fromTime, untilTime, fieldCsv}) {
|
|
10
|
+
const opts = {
|
|
11
|
+
fromTime,
|
|
12
|
+
untilTime,
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const attemptDeleteFieldLocator = async fieldLocator => {
|
|
16
|
+
try {
|
|
17
|
+
await fieldDataClient.deleteFieldData({
|
|
18
|
+
fieldLocator,
|
|
19
|
+
opts,
|
|
20
|
+
})
|
|
21
|
+
cli.log(`successfully deleted execution data for fieldId=${fieldLocator.fieldId} jobBaseStepId=${fieldLocator.jobBaseStepId}`)
|
|
22
|
+
} catch (error) {
|
|
23
|
+
render.renderException(error)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const attemptDeleteFieldLocatorRateLimited = async fieldLoc => {
|
|
28
|
+
return delayResolve(async () => {
|
|
29
|
+
await attemptDeleteFieldLocator(fieldLoc)
|
|
30
|
+
}, DELAY)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (typeof fieldId !== 'undefined' && typeof jobBaseStepId !== 'undefined') {
|
|
34
|
+
// if field and job-base-step ids supplied inline, then make a locator and call deleter function
|
|
35
|
+
await attemptDeleteFieldLocator({fieldId, jobBaseStepId})
|
|
36
|
+
} else {
|
|
37
|
+
// else, it's a csv
|
|
38
|
+
await serialAsyncCsvReader(fieldCsv, ['fieldId', 'jobBaseStepId'], attemptDeleteFieldLocatorRateLimited)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
const VError = require('verror')
|
|
2
|
+
|
|
3
|
+
module.exports = class VerrorException extends Error {
|
|
4
|
+
constructor(err) {
|
|
5
|
+
const verror = new VError(err)
|
|
6
|
+
super(verror.name)
|
|
7
|
+
|
|
8
|
+
this.name = 'VerrorException'
|
|
9
|
+
this.info = VError.info(verror)
|
|
10
|
+
this.cause = VError.cause(verror)
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
const csv = require('csv-parser')
|
|
2
|
+
const fs = require('fs')
|
|
3
|
+
|
|
4
|
+
module.exports = (csvPath, headers, func) => {
|
|
5
|
+
return new Promise((resolve, reject) => {
|
|
6
|
+
/*
|
|
7
|
+
* There's some weirdness here in the way the stream sends us 'data' and 'end' events.
|
|
8
|
+
* 'end' is fired after the last row is sent to the 'data' handler, but often before
|
|
9
|
+
* the 'data' handler is finished processing.
|
|
10
|
+
*
|
|
11
|
+
* So there's two ways it can go:
|
|
12
|
+
* 1. 'end' handler is invoked before the final 'data' handler completes
|
|
13
|
+
* - in this case, we want the 'data' handler to resolve when it's complete
|
|
14
|
+
* 2. 'end' hander is invoked after the final 'data' handler completes
|
|
15
|
+
* - in this case, we want the 'end' handler to resolve
|
|
16
|
+
*
|
|
17
|
+
* So the strategy is:
|
|
18
|
+
* - if 'end' handler is called, it checks to see if there are any 'data' handlers still running
|
|
19
|
+
* by using the rowInProgress variable. If yes, then it resolves. If no, then it sets isLastRow
|
|
20
|
+
* to true.
|
|
21
|
+
* - when 'data' handlers are called, they set rowInProgress to true while they're processing. If
|
|
22
|
+
* when they complete, they find that isLastRow is true, then they resolve.
|
|
23
|
+
*/
|
|
24
|
+
let isLastRow = false
|
|
25
|
+
let rowInProgress = false
|
|
26
|
+
|
|
27
|
+
const stream = fs.createReadStream(csvPath)
|
|
28
|
+
.on('error', reject)
|
|
29
|
+
|
|
30
|
+
.pipe(csv(headers))
|
|
31
|
+
|
|
32
|
+
.on('data', async row => {
|
|
33
|
+
stream.pause()
|
|
34
|
+
rowInProgress = true
|
|
35
|
+
await func(row)
|
|
36
|
+
rowInProgress = false
|
|
37
|
+
stream.resume()
|
|
38
|
+
|
|
39
|
+
if (isLastRow) {
|
|
40
|
+
resolve()
|
|
41
|
+
}
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
.on('end', () => {
|
|
45
|
+
const processingComplete = !rowInProgress
|
|
46
|
+
if (processingComplete) {
|
|
47
|
+
resolve()
|
|
48
|
+
} else {
|
|
49
|
+
isLastRow = true
|
|
50
|
+
}
|
|
51
|
+
})
|
|
52
|
+
})
|
|
53
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
const _get = require('lodash/get')
|
|
2
|
+
const debug = require('debug')('app:services:jobs:CreateFunction')
|
|
3
|
+
const path = require('path')
|
|
4
|
+
|
|
5
|
+
module.exports = function ({mothershipClient, currentEnv}) {
|
|
6
|
+
return async function ({teamId, title, templateId}) {
|
|
7
|
+
try {
|
|
8
|
+
const url = path.join(currentEnv.url, 'api', 'jobs')
|
|
9
|
+
|
|
10
|
+
const getJobRolesPayload = {
|
|
11
|
+
method: 'index',
|
|
12
|
+
arguments: {
|
|
13
|
+
teamId,
|
|
14
|
+
opts: {
|
|
15
|
+
showArchived: false,
|
|
16
|
+
},
|
|
17
|
+
selectOpts: {
|
|
18
|
+
allUsers: true,
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const getJobRolesResponse = await mothershipClient.post(`${currentEnv.url}/api/job_roles`, {
|
|
24
|
+
json: getJobRolesPayload,
|
|
25
|
+
headers: {
|
|
26
|
+
Authorization: `Token ${currentEnv.token}`,
|
|
27
|
+
},
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
debug(`getJobRolesPayload=${JSON.stringify(getJobRolesPayload)}`)
|
|
31
|
+
|
|
32
|
+
const jobRoles = _get(getJobRolesResponse, ['body', 'result', 'success'], [])
|
|
33
|
+
|
|
34
|
+
const getJobRolesError = _get(getJobRolesResponse, ['body', 'result', 'err'])
|
|
35
|
+
|
|
36
|
+
if (getJobRolesError) {
|
|
37
|
+
throw new Error(`Failed to create job due to error: ${JSON.stringify(getJobRolesError)}`)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const jobRoleId = jobRoles.find(item => item.name === 'Job Planner').id || ''
|
|
41
|
+
|
|
42
|
+
const createJobPayload = {
|
|
43
|
+
method: 'createBlank',
|
|
44
|
+
arguments: {
|
|
45
|
+
teamId,
|
|
46
|
+
params: {
|
|
47
|
+
title,
|
|
48
|
+
skipPlanning: false,
|
|
49
|
+
typ: 4,
|
|
50
|
+
plannedStartJobRoleIds: [jobRoleId],
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
debug(`createJobPayload=${JSON.stringify(createJobPayload)}`)
|
|
56
|
+
|
|
57
|
+
const createJobResponse = await mothershipClient.post(url, {
|
|
58
|
+
json: createJobPayload,
|
|
59
|
+
headers: {
|
|
60
|
+
Authorization: `Token ${currentEnv.token}`,
|
|
61
|
+
},
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
const jobId = _get(createJobResponse, ['body', 'result', 'success', 'id'])
|
|
65
|
+
|
|
66
|
+
const createJobError = _get(createJobResponse, ['body', 'result', 'err'])
|
|
67
|
+
|
|
68
|
+
if (createJobError) {
|
|
69
|
+
throw new Error(`Failed to create job due to error: ${JSON.stringify(createJobError)}`)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (templateId) {
|
|
73
|
+
const addTemplateToJobPayload = {
|
|
74
|
+
method: 'addTemplates',
|
|
75
|
+
arguments: {
|
|
76
|
+
jobId,
|
|
77
|
+
templateIds: [templateId],
|
|
78
|
+
position: 0,
|
|
79
|
+
},
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
debug(`addTemplateToJobPayload=${JSON.stringify(addTemplateToJobPayload)}`)
|
|
83
|
+
|
|
84
|
+
const addTemplateToJobResponse = await mothershipClient.post(url, {
|
|
85
|
+
json: addTemplateToJobPayload,
|
|
86
|
+
headers: {
|
|
87
|
+
Authorization: `Token ${currentEnv.token}`,
|
|
88
|
+
},
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
const jobTemplateId = _get(addTemplateToJobResponse, ['body', 'result', 'success', 'jobTemplateId'])
|
|
92
|
+
const addTemplateToJobError = _get(addTemplateToJobResponse, ['body', 'result', 'err'])
|
|
93
|
+
|
|
94
|
+
if (addTemplateToJobError) {
|
|
95
|
+
throw new Error(`Failed to add template id ${templateId} to job id ${jobId} due to error: ${JSON.stringify(addTemplateToJobError)}`)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return {jobId, title, templateId: jobTemplateId}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return {jobId, title, templateId}
|
|
102
|
+
} catch (error) {
|
|
103
|
+
throw new Error(error.message)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
const fs = require('fs')
|
|
2
|
+
const {cli} = require('cli-ux')
|
|
3
|
+
const _get = require('lodash/get')
|
|
4
|
+
const debug = require('debug')('app:services:jobs:DeleteFunction')
|
|
5
|
+
|
|
6
|
+
const DESCENDANT_OUTPUT_CSV = 'descendant-%JOBTYPE%s.csv'
|
|
7
|
+
|
|
8
|
+
module.exports = function ({adminClient}) {
|
|
9
|
+
return async ({teamId, jobsCsv, issuesCsv}) => deleteJobsCsvsAndPrintDescendants(teamId, jobsCsv, issuesCsv, adminClient)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const deleteJobsCsvsAndPrintDescendants = async (teamId, jobsCsv, issuesCsv, adminClient) => {
|
|
13
|
+
let jobsResult
|
|
14
|
+
let issuesResult
|
|
15
|
+
let allDescendants
|
|
16
|
+
|
|
17
|
+
if (jobsCsv) {
|
|
18
|
+
debug(`deleting ${teamId} jobs with csv=${jobsCsv}`)
|
|
19
|
+
jobsResult = await deleteJobsCsv(teamId, jobsCsv, 'job', adminClient)
|
|
20
|
+
allDescendants = jobsResult.descendants
|
|
21
|
+
}
|
|
22
|
+
if (issuesCsv) {
|
|
23
|
+
debug(`deleting ${teamId} issues with csv=${issuesCsv}`)
|
|
24
|
+
issuesResult = await deleteJobsCsv(teamId, issuesCsv, 'issue', adminClient)
|
|
25
|
+
allDescendants = combineDescendantsMaps(allDescendants, issuesResult.descendants)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
debug(`descendants found ${JSON.stringify(allDescendants, null, 2)}`)
|
|
29
|
+
printDescendantsCsv(allDescendants.level2.issues.concat(allDescendants.level1.issues), 'issue', teamId)
|
|
30
|
+
printDescendantsCsv(allDescendants.level2.jobs.concat(allDescendants.level1.jobs), 'job', teamId)
|
|
31
|
+
printDeletionStats('job', jobsResult)
|
|
32
|
+
printDeletionStats('issue', issuesResult)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const deleteJobsCsv = async (teamId, csv, jobType, adminClient) => {
|
|
36
|
+
let accumDescendants = combineDescendantsMaps(null, null)
|
|
37
|
+
let result = createStats()
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
debug(`opening csv=${csv}`)
|
|
41
|
+
fs.accessSync(csv, fs.constants.F_OK | fs.constants.R_OK)
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (error) {
|
|
44
|
+
if (error.code === 'ENOENT') {
|
|
45
|
+
cli.error(`No file found at ${csv}`)
|
|
46
|
+
} else {
|
|
47
|
+
cli.error(`User does not have read permissions for file at ${csv}`)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const lines = fs.readFileSync(csv).toString().split('\n')
|
|
53
|
+
for (let key of lines) {
|
|
54
|
+
try {
|
|
55
|
+
key = key.trim()
|
|
56
|
+
if (!key) {
|
|
57
|
+
continue
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
result.total++
|
|
61
|
+
const id = await getJobIdFromKey(teamId, key, jobType, adminClient, result)
|
|
62
|
+
|
|
63
|
+
if (id) {
|
|
64
|
+
const descendants = await deleteJobById(teamId, id, jobType, adminClient, result)
|
|
65
|
+
if (descendants) {
|
|
66
|
+
accumDescendants = combineDescendantsMaps(accumDescendants, descendants)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
} catch (error) {
|
|
70
|
+
result.errors++
|
|
71
|
+
cli.warn(`Failed to delete ${jobType} ${key}: ${error} ${JSON.stringify(adminClient)}`)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
result.descendants = accumDescendants
|
|
76
|
+
return result
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const getJobIdFromKey = async (teamId, key, jobType, adminClient, stats) => {
|
|
80
|
+
let lookupId
|
|
81
|
+
const prefix = jobType === 'issue' ? 'Issue-' : 'Job-'
|
|
82
|
+
if (key.startsWith(prefix)) {
|
|
83
|
+
lookupId = key
|
|
84
|
+
} else if (/^\d+$/.test(key)) {
|
|
85
|
+
lookupId = `${prefix}${key}`
|
|
86
|
+
} else {
|
|
87
|
+
return key
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const response = await adminClient.getJobByLookupId(teamId, lookupId)
|
|
91
|
+
if (response.status === 200) {
|
|
92
|
+
return response?.body?.job?.id
|
|
93
|
+
} else if (response.status === 404) {
|
|
94
|
+
stats.notFound++
|
|
95
|
+
} else {
|
|
96
|
+
stats.errors++
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
cli.warn(`Error code ${response.status}, message "${response.body.message}" while getting ID for job ${lookupId}`)
|
|
100
|
+
return ''
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const deleteJobById = async (teamId, id, jobType, adminClient, stats) => {
|
|
104
|
+
debug(`deleting ${jobType} '${id}'`)
|
|
105
|
+
const response = await adminClient.deleteJobById(teamId, id, jobType)
|
|
106
|
+
|
|
107
|
+
if (response.status === 200) {
|
|
108
|
+
stats.deleted++
|
|
109
|
+
debug(`successfully deleted ${jobType} ${id}`)
|
|
110
|
+
cli.log(`Deleted ${jobType} ${id}`)
|
|
111
|
+
} else {
|
|
112
|
+
debug(`error deleting ${jobType} id ${id}: ${_get(response, ['body', 'message'], '<unspecified>')}`)
|
|
113
|
+
if (response.status === 404) {
|
|
114
|
+
stats.notFound++
|
|
115
|
+
} else {
|
|
116
|
+
stats.errors++
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const errDescendants = _get(response, ['body', 'details', 'descendants'])
|
|
120
|
+
if (errDescendants) {
|
|
121
|
+
cli.warn(`Failed to delete ${jobType} ${id} due to descendant jobs/issues`)
|
|
122
|
+
return errDescendants
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const msg = _get(response, ['body', 'message'], '<unspecified>')
|
|
126
|
+
cli.warn(`Failed to delete ${jobType} ${id} due to error: ${msg}`)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const printDescendantsCsv = (descendants, jobType, teamId) => {
|
|
131
|
+
if (descendants.length === 0) {
|
|
132
|
+
return
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const csvPath = DESCENDANT_OUTPUT_CSV.replace('%JOBTYPE%', jobType)
|
|
136
|
+
const outputCsv = fs.openSync(csvPath, 'w')
|
|
137
|
+
for (const desc of descendants) {
|
|
138
|
+
fs.writeSync(outputCsv, `${desc}\n`)
|
|
139
|
+
}
|
|
140
|
+
cli.warn(`Descendant ${jobType}s prevented successful deletion of all jobs in the input CSV.
|
|
141
|
+
Re-run the deletion command on the CSV "${csvPath}" to delete those descendant ${jobType}s,
|
|
142
|
+
then re-run it on the original CSV to complete the deletion
|
|
143
|
+
For example:
|
|
144
|
+
|
|
145
|
+
> parsable-cli jobs:delete --team-id ${teamId} --${jobType}s-csv ${csvPath}
|
|
146
|
+
`)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const printDeletionStats = (jobType, stats) => {
|
|
150
|
+
if (stats) {
|
|
151
|
+
cli.info(`Total ${jobType}s:\t${stats.total}\tDeleted: ${stats.deleted}\tNot found: ${stats.notFound}\tErrors: ${stats.errors}`)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const createStats = () => {
|
|
156
|
+
return {
|
|
157
|
+
total: 0,
|
|
158
|
+
deleted: 0,
|
|
159
|
+
notFound: 0,
|
|
160
|
+
errors: 0,
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const combineDescendantsMaps = (d1, d2) => {
|
|
165
|
+
return {
|
|
166
|
+
level1: {
|
|
167
|
+
jobs: _get(d1, ['level1', 'jobs'], []).concat(_get(d2, ['level1', 'jobs'], [])),
|
|
168
|
+
issues: _get(d1, ['level1', 'issues'], []).concat(_get(d2, ['level1', 'issues'], [])),
|
|
169
|
+
},
|
|
170
|
+
level2: {
|
|
171
|
+
jobs: _get(d1, ['level2', 'jobs'], []).concat(_get(d2, ['level2', 'jobs'], [])),
|
|
172
|
+
issues: _get(d1, ['level2', 'issues'], []).concat(_get(d2, ['level2', 'issues'], [])),
|
|
173
|
+
},
|
|
174
|
+
}
|
|
175
|
+
}
|